Search code examples
javafileinputstreamfileoutputstream

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?


Solution

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