【问题标题】:File copying: what am I doing wrong?文件复制:我做错了什么?
【发布时间】:2016-03-17 21:45:22
【问题描述】:

对不起,

我没有使用 Android 文件系统的经验,我很难通过文档和教程来理解它。

我正在尝试将文件从某个位置复制到我的应用的外部存储。

    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;
}

我收到以下错误:

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)

【问题讨论】:

  • 异常告诉你试图复制的文件实际上是一个目录。您是否验证它确实是一个文件?无论如何,哪一行会引发异常?
  • 在这里你得到 13.18.14.jpg 作为你的文件名,然后你调用 file.mkdirs() 。可能的帮助stackoverflow.com/questions/12339673/… .
  • @user714965 我想做的是用final File destination = new File(path,item.getName()); 创建目标文件,其中 path 确实是一个目录,item.getName() 是一个应该是的字符串文件名
  • 您是否尝试打印pathitem.getName() 的值?还要确保在清单文件中添加WRITE_EXTERNAL_STORAGE 权限。

标签: android


【解决方案1】:

【讨论】:

    【解决方案2】:

    试试

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

    改为。

    【讨论】:

    • 这不会改变任何事情。
    【解决方案3】:

    我假设,文件夹目录没有创建或者你的外部存储状态没有挂载。

    在执行文件操作之前,您应该清理您的路径。以下代码是我经常使用的示例代码。

    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;
        }
    

    并确保在执行文件操作之前必须创建目录时。

    希望这会有所帮助。

    编辑:顺便说一句,您必须在 manifest.xml 文件中添加以下权限

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

    【讨论】:

      猜你喜欢
      • 2019-12-21
      • 1970-01-01
      • 2013-08-10
      • 2012-07-07
      • 1970-01-01
      • 2021-12-03
      • 2016-03-22
      • 2016-06-02
      • 1970-01-01
      相关资源
      最近更新 更多