我想使用 bufferedInputStream
和 bufferedOutputStream
将大型二进制文件从源文件复制到目标文件。
这是我的代码:
byte[] buffer = new byte[1000];
try {
FileInputStream fis = new FileInputStream(args[0]);
BufferedInputStream bis = new BufferedInputStream(fis);
FileOutputStream fos = new FileOutputStream(args[1]);
BufferedOutputStream bos = new BufferedOutputStream(fos);
int numBytes;
while ((numBytes = bis.read(buffer))!= -1)
{
bos.write(buffer);
}
//bos.flush();
//bos.write("\u001a");
System.out.println(args[0]+ " is successfully copied to "+args[1]);
bis.close();
bos.close();
} catch (IOException e)
{
e.printStackTrace();
}
我可以成功复制但是然后我使用
cmp src dest
在命令行中比较两个文件。 错误信息
cmp: EOF on files
出现。我可以知道我哪里错了吗?
最佳答案
这是错误的:
bos.write(buffer);
您正在写出整个 缓冲区,即使您只将数据读入其中的部分。你应该使用:
bos.write(buffer, 0, numBytes);
如果您使用的是 Java 7 或更高版本,我还建议您使用 try-with-resources,否则将 close
调用放在 finally
block 中。
正如 Steffen 所说,Files.copy
如果可以的话,这是一种更简单的方法。
关于java - JAVA中如何通过bufferedInputStream和bufferedOutputStream复制文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28107668/