3 java bufferedinputstream eof bufferedoutputstream
我想用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();
}
Run Code Online (Sandbox Code Playgroud)
我可以成功复制,但后来我使用
cmp src dest
Run Code Online (Sandbox Code Playgroud)
在命令行中比较两个文件.错误消息
cmp:文件上的EOF
出现.我可以知道我哪里错了吗?
这是错误的:
bos.write(buffer);
Run Code Online (Sandbox Code Playgroud)
您正在写出整个缓冲区,即使您只将数据读入其中的一部分.你应该使用:
bos.write(buffer, 0, numBytes);
Run Code Online (Sandbox Code Playgroud)
如果您使用的是Java 7或更高版本,我还建议使用try-with-resources,否则将close调用放入finally块中.
正如Steffen指出的那样,Files.copy如果您可以使用这种方法,则更简单.
| 归档时间: |
|
| 查看次数: |
5197 次 |
| 最近记录: |