需求:
项目中,需要从手机上选择文件,复制到项目的文件夹下
原方案:
/** 调用文件选择软件来选择文件 **/
private void showFileChooser() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
<span style="white-space:pre"> </span>//100随你自己写,但需要 > 0 作为返回时的判断,可以定义为static final int常量
startActivityForResult(Intent.createChooser(intent, "请选择一个文件"), 100);
} catch (android.content.ActivityNotFoundException ex) {
// Potentially direct the user to the Market with a Dialog
Toast.makeText(this, "请安装文件管理器", Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 100) // 自定义int常量与startActivityForResult设置的100对应
{
if (resultCode == RESULT_OK) {
// 得到文件的Uri
Uri uri = data.getData();
<span style="white-space:pre"> </span>//两个方法类似返回类型不同
String uri1 = data.getDataString();//daa.getData.toString()
ContentResolver resolver = getContentResolver();
// ContentResolver对象的getType方法可返回形如content://的Uri的类型
<span style="white-space:pre"> </span>//文件类型为null
String fileType = resolver.getType(uri);
//不做这步,file.exists()为null
String fileUrl = uri1.replace("file://", "");</span></span>
File file = new File(fileName);
//获取文件名带后缀
String fileName = file.getName();
Log.i("文件信息", "uri" + "=" + uri);
Log.i("文件信息", "fileUrl" + "=" + fileUrl);
Log.i("文件信息", "fileName" + "=" + fileName);
Log.i("文件信息", "fileType" + "=" + fileType);
Log.i("文件信息", "file.exists()" + "=" + file.exists());
copyFile(fileName, Environment.getExternalStorageDirectory() + "/"+fileName);
}
}
}
copyFile方法
<span style="white-space:pre"> </span>/**
* 复制文件到指定目录,可以作为工具方法
*
* @param oldPath
* 需要复制的文件
* @param newPath
* 新文件路径,目录必须是存在的
*/
public static void copyFile(String oldPath, String newPath) {
try {
int bytesum = 0;
int byteread = 0;
File oldfile = new File(oldPath);
if (oldfile.exists()) { // 文件存在时
InputStream inStream = new FileInputStream(oldPath); // 读入原文件
FileOutputStream fs = new FileOutputStream(newPath);
byte[] buffer = new byte[1444];
int length;
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread; // 字节数 文件大小
System.out.println(bytesum);
fs.write(buffer, 0, byteread);
}
inStream.close();
} else {
System.out.println("复制单个文件操作出错----");
}
} catch (Exception e) {
System.out.println("复制单个文件操作出错" + e);
e.printStackTrace();
}
}
扫描二维码关注公众号,回复:
2180274 查看本文章
输出:
到这里,没什么问题了,但是我发现去复制带中文名的文件时,file.exists()=null;
输出:
发现中文进行了编码
查询资料,linux下面的编码方式为UTF-8,而android的内核为linux,
Uri.decode()---使用了utf-8的编码
把
String uri1 = data.getDataString();
换成
String uri1= Uri.decode(data.getDataString());
后面的不变就可以了
输出:
到此就解决了