2013-10-29 77 views
2

我能够得到我想要复制的图片的路径,并且能够从我想要复制的位置获得路径,但仍然无法找到复制它们的方式。 有什么建议吗?创建一个SD卡图片副本到另一个目录?

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

    } 

谢谢。

回答

1

您应该使用Commons-IO复制文件,我们在2013年!没有人想要手动做这件事。如果你真的那么你应该考虑几件事情:

  • 第一个循环,拷贝文件,在每次迭代复制buffer.length字节。在你当前的代码中,你不会循环并将512字节的源图像复制到dest中(无论源图像的大小是多少)。
  • 照顾最后一次迭代,只复制你读的内容
  • 你的try/catch结构不正确,你应该添加一个finally关闭来始终关闭你的源文件和目标文件。看看这里的一个例子: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); 
} 

,不捉任何东西,它会转发给调用者。