How to copy files in Java through bufferedinputstream and bufferedoutputstream?
•
Java
I want to use bufferedinputstream and bufferedoutputstream to copy large binaries from the source file to the target file
This is my code:
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();
}
I can copy it successfully, but then I use it
cmp src dest
Compare two files on the command line Error message
appear. Can I know what's wrong with me?
Solution
This is wrong:
bos.write(buffer);
You are writing out the entire buffer, even if you read only part of it You should use:
bos.write(buffer,numBytes);
If you are using java 7 or later, I also recommend using try with resources, otherwise put the close call in the finally block
As Steffen said, if you can use files Copy is a simpler method
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
