在 android 中传输文件

Transferring a File in android

我折腾了两天,想弄懂Android中复制一个文件到SD卡的过程。 None 到目前为止我尝试过的方法似乎有效。

我的应用程序有个人资料图片设置。我需要启动一个 Intent 来选择一个图像,然后我需要将图像复制到 SD 卡上的一个新路径,然后 return 新图像的 Uri,此时我检查图像方向(Samsung Pics有时似乎旋转了 90 度)。然后我正确旋转图像,然后将 Uri 保存到 SharedPreferences 文件以供在应用程序中使用。

这是我的意向电话:

case R.id.ib_userImage:

    i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
    startActivityForResult(i, 1);
    break;

这是我目前对复制功能的可怕尝试,我改了这么多,我不是很迷茫。

public static void copyImage(Context context, 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();

并删除多余的存在性检查。目前您正在将文件本身创建为目录。