Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

copy file in Java using FileStream

I want to copy a file in Java using FileStream. This is my code.

FileInputStream infile = new FileInputStream("in");
FileOutputStream outfile = new FileOutputStream("out");

byte[] b = new byte[1024];
while(infile.read(b, 0, 1024) > 0){
    outfile.write(b);
}

infile.close();
outfile.close();

I use vim to view my file.
Input file "in"

Hello World1
Hello World2
Hello World3

Output file "output"

Hello World1
Hello World2
Hello World3
^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@...

There are many extra '^@' in the output file.
Size of input file is 39 Bytes.
And size of output file is 1KB.
Why that there are many extra char in the output file?

like image 325
Larry Lu Avatar asked Sep 29 '26 01:09

Larry Lu


2 Answers

When you call infile.read, the return value tells you how many items you are getting back. When you call outfile.write, you tell it that the buffer is filled, because you did not store the number of bytes that you got back from the read call.

To fix this problem store the number of bytes, then pass the proper number to write:

byte[] b = new byte[1024];
int len;
while((len = infile.read(b, 0, 1024)) > 0){
    outfile.write(b, 0, len);
}
like image 177
Sergey Kalinichenko Avatar answered Sep 30 '26 14:09

Sergey Kalinichenko


You are trying to copy 1024 bytes from the file to another. That will not work well. Try to read by the size of the file.

FileInputStream infile = new FileInputStream("in");
FileOutputStream outfile = new FileOutputStream("out");

byte[] b = new byte[infile.getChannel().size()];
while(infile.read(b, 0, infile.getChannel().size()) > 0){
    outfile.write(b);
}

infile.close();
outfile.close();
like image 39
DDan Avatar answered Sep 30 '26 14:09

DDan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!