【问题标题】:Copying file (img/doc) from a specific path to another in Android在Android中将文件(img / doc)从特定路径复制到另一个路径
【发布时间】:2013-03-12 07:30:37
【问题描述】:

我的应用程序中有一个功能,可以在我的数据库中保存一个 doc/img 文件路径。该文件位于文件夹中(例如“/mnt/sdcard/MyApp/MyItem/test.png”)。现在我要做的是将此文件复制到其他文件夹(例如/mnt/sdcard/MyApp/MyItem/Today/test.png)。

现在我正在使用下面的代码,但它不起作用:

private void copyDirectory(File from, File to) throws IOException {


    try {
        int bytesum = 0;
        int byteread = 0;

            InputStream inStream = new FileInputStream(from);
            FileOutputStream fs = new FileOutputStream(to);
            byte[] buffer = new byte[1444];
            while ((byteread = inStream.read(buffer)) != -1) {
                bytesum += byteread;
                fs.write(buffer, 0, byteread);
            }
            inStream.close();
            fs.close();

    } catch (Exception e) {
    }
}

然后点击按钮,使用以下代码:

File sourceFile = new File(fileList.get(0).getAbsolutePath); //comes from dbs File targetFile = new File(Environment.getExternalStorageDirectory(),"MyApp/MyItem/Today/"); copyDirectory(sourceFile,targetFile, currDateStr);

知道为什么它不起作用吗?

【问题讨论】:

  • 尝试调用 fs.flush();

标签: android file-io


【解决方案1】:

这段代码对我来说很好用。

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

您在清单文件中添加了另外一件事*写入外部存储的权限。*

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

【讨论】:

    【解决方案2】:

    是的,它工作了,我在复制文件时没有给出文件名,也没有真正查看错误日志,现在可以工作了,谢谢。是的,上面的代码工作得很好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-31
      • 1970-01-01
      • 1970-01-01
      • 2016-08-29
      • 2013-05-29
      • 1970-01-01
      相关资源
      最近更新 更多