我花了两天时间尝试理解在 Android 中将文件复制到 SD 卡的过程。到目前为止我尝试过的方法似乎都不起作用。
我的应用程序有一个个人资料图片设置。我需要启动一个 Intent 来选择图像,然后我需要将图像复制到 SD 卡上的新路径,然后返回新图像的 Uri,此时我检查图像方向(三星图片似乎已旋转)有时为 90 度)。然后,我正确旋转图像,然后将 Uri 保存到 SharedPreferences 文件以在应用程序中使用。
这是我的 Intent 调用:
case R.id.ib_userImage:
i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(i, 1);
break;
这是我目前对复制功能的可怕尝试,我已经改变了很多,我并没有很迷失。
公共(public)静态无效copyImage(上下文上下文,Uri uri){
Log.i("ATTENTION", "Inside the Copy Function");
Log.i("ATTENTION", "Trying to copy file: " + uri.toString());
try {
String outputPath = Environment.getExternalStorageDirectory() + "/appname/images/";
File dir = new File(outputPath);
if(!dir.exists()) {
dir.mkdirs();
}
Log.i("ATTENTION", "Destination File Created at: " + dir.toURI().toString());
InputStream in = context.getContentResolver().openInputStream(uri);
OutputStream out = new FileOutputStream(dir);
byte[] buffer = new byte[1024];
while(in.read(buffer) > 0) {
out.write(buffer);
}
out.flush();
out.close();
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Log.i("ATTENTION", "File Copied");
}
感谢您的帮助,我将提供您可能需要的任何其他信息。
更新:
我现在在写入过程中遇到以下异常
java.io.FileNotFoundException:/storage/emulated/0/appname/images:打开失败:EISDIR(是目录);
我的理解是我使用以下代码指定了一个目录:
String outputPath = Environment.getExternalStorageDirectory() + "/medinfo/images/";
File dir = new File(outputPath);
if(!dir.exists()) {
dir.mkdirs();
}
然后将其传递给OutputStream:
OutputStream out = new FileOutputStream(dir);
OutputStream 会在该目录中为我创建文件。
我认为这实际上并不是在尝试打开目录。
最佳答案
常见问题。不要忽略 read() 返回的计数。
while ((count = in,read(buffer)) > 0)
{
out.write(buffer, 0, count);
}
编辑您的目录问题已通过以下方式解决:
dir.getParentFile().mkdirs();
并删除冗余存在检查。目前您正在将文件本身创建为目录。
关于java - 在android中传输文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29423643/