【问题标题】:creating a copy of sdcard picture to another directory?将 sdcard 图片的副本创建到另一个目录?
【发布时间】:2013-10-29 22:26:34
【问题描述】:

我能够获得我想要复制的图片的路径,并且能够从我想要复制的位置获得路径,但仍然找不到复制它们的方法。 有什么建议吗?

private void copyPictureToFolder(String picturePath, String folderName)
            throws IOException {
        Log.d("debug", folderName);
        Log.d("debug", picturePath);

        try {
            FileInputStream fileInputStream = new FileInputStream(picturePath);
            FileOutputStream fileOutputStream = new FileOutputStream(folderName+"/");

            int bufferSize;
            byte[] bufffer = new byte[512];
            while ((bufferSize = fileInputStream.read(bufffer)) > 0) {
                fileOutputStream.write(bufffer, 0, bufferSize);
            }
            fileInputStream.close();
            fileOutputStream.close();
        } catch (Exception e) {
            Log.d("disaster","didnt work");
        }

    }

谢谢。

【问题讨论】:

    标签: android


    【解决方案1】:

    您应该使用Commons-IO 来复制文件,我们是2013 年!没有人愿意手动执行此操作。如果你真的想要那么你应该考虑一些事情:

    • 首先是一个复制文件的循环,在每次迭代时复制 buffer.length 个字节。在您当前的代码中,您不会循环并将 512 字节的源图像复制到 dest(无论源图像大小如何)。
    • 注意最后一次迭代,只复制您阅读的内容
    • 您的 try/catch 结构不正确,您应该添加 finally close 以始终关闭源文件和目标文件。看这里的例子:what is the exact order of execution for try, catch and finally?

    使用 IOUtils,它会给出类似

    try {
      IOUtils.copy( source, dest );
    } finally {
      IOUtils.closeQuietly( source );
      IOUtils.closeQuietly( dest );
    }
    

    并且不捕获任何东西,它将被转发给调用者。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-13
      • 2021-09-19
      • 2011-04-20
      • 1970-01-01
      相关资源
      最近更新 更多