【发布时间】:2011-07-20 06:39:12
【问题描述】:
我有一个文件 example.tar.gz,我需要将它复制到另一个名称不同的位置 例如 _test.tar.gz。我试过了
private void copyFile(File srcFile, File destFile) throws IOException {
InputStream oInStream = new FileInputStream(srcFile);
OutputStream oOutStream = new FileOutputStream(destFile);
// Transfer bytes from in to out
byte[] oBytes = new byte[1024];
int nLength;
BufferedInputStream oBuffInputStream = new BufferedInputStream(oInStream);
while((nLength = oBuffInputStream.read(oBytes)) > 0) {
oOutStream.write(oBytes, 0, nLength);
}
oInStream.close();
oOutStream.close();
}
在哪里
String from_path = new File("example.tar.gz");
File source = new File(from_path);
File destination = new File("/temp/example_test.tar.gz");
if(!destination.exists())
destination.createNewFile();
然后
copyFile(source, destination);
它不起作用。路径是正确的。它打印文件存在。有人可以帮帮我吗?
【问题讨论】:
-
在
close()之前尝试flush()您的流。 -
在您的帖子中更正此代码:
String from_path=new File("example.tar.gz"); -
@Mohamed,关闭之前不需要刷新
-
你不需要带有 FileOutputStream 的 createNewFile,你也不应该使用 BufferedInputStream(),它并没有真正的帮助。只需使用大于 1k 的
byte[] oBytes。最后但同样重要的是,FileChannel.transferTo是复制Stuff 的最佳方式
标签: java