如何通过bufferedInputStream和bufferedOutputStream复制JAVA中
发布时间:2020-12-15 04:45:02 所属栏目:Java 来源:网络整理
导读:我想使用bufferedInputStream和bufferedOutputStream将大型二进制文件从源文件复制到目标文件. 这是我的代码: byte[] buffer = new byte[1000]; try { FileInputStream fis = new FileInputStream(args[0]); BufferedInputStream bis = new BufferedInputSt
我想使用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 在命令行中比较两个文件.
出现.我可以知道我哪里错了吗? 解决方法
这是错误的:
bos.write(buffer); 您正在写出整个缓冲区,即使您只将数据读入其中的一部分.你应该使用: bos.write(buffer,numBytes); 如果您使用的是Java 7或更高版本,我还建议使用try-with-resources,否则将close调用放在finally块中. 正如Steffen所说,如果您可以使用 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |