Larry Lu
Larry Lu

Reputation: 1661

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?

Upvotes: 3

Views: 6448

Answers (4)

Andriy Kryvtsun
Andriy Kryvtsun

Reputation: 3344

The easiest way to copy file is a call of the single method
1. before Java 7 - from Google Guava library
com.google.common.io.Files#copy(File from, File to)
2. in Java 7 & 8
java.nio.file.Files#copy(Path source, Path target, CopyOption... options)

Upvotes: 0

Sanket Gupte
Sanket Gupte

Reputation: 357

The size of the array b[] is 1KB. The extra character '@' is appended to show that the file still has space that is left unutilized. Technically you are copying a file in a byte array and writing the but array in the output file. That is why this problem occurs.

Upvotes: 0

DDan
DDan

Reputation: 8276

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();

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726589

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);
}

Upvotes: 5

Related Questions