简体   繁体   English

文件复制:我在做什么错?

[英]File copying: what am I doing wrong?

Sorry, 抱歉,

I have no experience with the Android file system, I am struggling to understand it via the documentation and the tutorials. 我没有使用Android文件系统的经验,我正努力通过文档和教程来了解它。

I am trying to copy a file from a location to the external storage of my app. 我正在尝试将文件从某个位置复制到应用程序的外部存储。

    final File filetobecopied =item.getFile();
    File path=getPrivateExternalStorageDir(mContext);
    final File destination = new File(path,item.getName());
    try 
       {copy(filetobecopied,destination);
  } 
       catch (IOException e) {Log.e("",e.toString());}

public void copy(File src, File dst) throws IOException {
    InputStream in = new FileInputStream(src);
    OutputStream out = new FileOutputStream(dst);

    // Transfer bytes from in to out
    byte[] buf = new byte[1024];
    int len;
    while ((len = in.read(buf)) > 0) {
        out.write(buf, 0, len);
    }
    in.close();
    out.close();
    Toast.makeText(mContext,"COPIED",Toast.LENGTH_SHORT).show();
}

public File getPrivateExternalStorageDir(Context context) {
    File file = context.getExternalFilesDir(null);
    if (!file.mkdirs()) {
        Log.e("", "Directory not created");
    }
    return file;
}

I get the following error: 我收到以下错误:

09-18 10:14:04.260: E/(7089): java.io.FileNotFoundException: /storage/emulated/0/Android/data/org.openintents.filemanager/files/2013-08-24 13.18.14.jpg: open failed: EISDIR (Is a directory)

Try 尝试

final File destination = new File(path + "/" + item.getName());

instead. 代替。

I assume, folder directory is not created or your external storage state is not mounted. 我假设未创建文件夹目录,或者未安装外部存储状态。

Before you perform file operations, you should sanitize your path. 在执行文件操作之前,应清理路径。 Following code is a sample code that I often use. 以下代码是我经常使用的示例代码。

public File sanitizePath(Context context) {
        String state = android.os.Environment.getExternalStorageState();
        File folder = null;
        if (!state.equals(android.os.Environment.MEDIA_MOUNTED)) {
            folder = new File(context.getFilesDir() + path);
            // path is the desired location that must be specified in your code.
        }else{
            folder = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + path);
        }
        if (!folder.exists()){
            folder.mkdirs();
        }

        return folder;
    }

And be sure about that, when your directory has to be created before you perform file operations. 并确保执行文件操作之前必须创建目录的时间。

Hope this will help. 希望这会有所帮助。

EDIT: By the way, you have to add following permission to your manifest.xml file 编辑:顺便说一句,您必须向manifest.xml文件添加以下权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM