Android:打开失败:ENOENT没有这个文件或目录。

3

我知道有很多问题和我的问题相似。但是这个问题不同。我使用以下方法将文件从文件夹A复制到文件夹B,使用的是EXTERNAL_STORAGE

    public static String copyFile(String path) {
        String fileToName = String.valueOf(System.currentTimeMillis());

        File pathFrom = new File(path);
        File pathTo = new File(Environment.getExternalStorageDirectory() + "/.noname");
        File file = new File(pathTo, fileToName + ".bak");

        while (file.exists()) {
            fileToName = String.valueOf(System.currentTimeMillis());
            file = new File(pathTo, fileToName + ".bak");
        }

        InputStream in = null;
        OutputStream out = null;
        try {
            in = new FileInputStream(pathFrom);
            out = new FileOutputStream(file);

            byte[] data = new byte[in.available()];
            in.read(data);
            out.write(data);
            in.close();
            out.close();

        } catch (FileNotFoundException e) {
            Log.e(TAG, e.getMessage());
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }
        return file.getPath();
    }

路径参数为:"/storage/emulated/0/Download/image_preview.jpg"。 执行此方法时,我遇到了一个错误:/storage/emulated/0/Download/tree_leaves_sunlight.jpg: open failed: ENOENT (No such file or directory)。 文件夹.noname已经存在。 对于我的问题,有什么建议吗?
**更新:我使用ImageView打开此文件。当我不打开它时,我可以复制它。但是当我打开时,我遇到了这个错误。 PS:我在ImageView中预览图像。并且有一个Button复制图像。单击按钮执行将此图像复制到其他文件夹的方法。
1个回答

1
当您为父目录创建File对象时,请不要忘记实际创建此文件夹。 File pathTo = new File(Environment.getExternalStorageDirectory() + "/.noname")
 pathTo.mkdirs();

同时尝试在图库中打开您正在尝试复制的文件。它可能已经损坏,Android 无法打开它。


请看我的更新。当不打开文件时,这种方法运行良好。但是在那里,我使用ImageView打开了这个文件。 - Phan Sinh
你说的打开ImageView是什么意思?你把这个文件设置为背景了吗? - HellCat2405
哦!我在ImageView中预览图像。还有一个复制图像的Button。当点击Button时,执行将此图像复制到其他文件夹的方法。 - Phan Sinh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接