在android中传输文件

时间:2015-04-02 22:38:08

标签: java android stream media

我已经苦苦挣扎了两天,试图理解将文件复制到Android中的SD卡的过程。到目前为止,我尝试过的方法似乎都没有用。

我的应用程序有个人资料图片设置。我需要启动一个Intent来选择一个Image,然后我需要将Image复制到SD卡上的新路径然后返回新Image的Uri,此时我检查了Images Orientation(三星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:open failed:EISDIR(是一个目录);

我的理解是我使用以下代码指定了一个目录:

 String outputPath = Environment.getExternalStorageDirectory() + "/medinfo/images/";

    File dir = new File(outputPath);

    if(!dir.exists()) {
        dir.mkdirs();
    }

然后将其传递给OutputStream:

OutputStream out = new FileOutputStream(dir);

并且OutputStream将在该目录中为我创建文件。

我认为实际上并没有尝试打开目录。

1 个答案:

答案 0 :(得分:1)

常见问题。不要忽略read().

返回的计数
while ((count = in,read(buffer)) > 0)
{
    out.write(buffer, 0, count);
}

编辑您的目录问题可通过以下方式解决:

dir.getParentFile().mkdirs();

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