0

我的应用程序中有一个功能,可以在我的数据库中保存一个 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);

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

4

2 回答 2

0

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

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" />
于 2013-03-12T07:47:24.137 回答
0

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

于 2013-03-12T09:17:07.650 回答