Search code examples
javaioinputstream

Copying a file byte-by-byte using DataInputStream stops before completion


I have written the following program in java to copy file using DataInput\Output Stream.

import java.io.*;
public class FileCopier {

    public static void main(String args[]) throws Exception
    {
        File file = new File("/home/Sample.mkv");
        File copy = new File("/home/Copy_of_Sample.mkv");
        if(copy.exists())
        {
            copy.delete();
        }
        copy.createNewFile();
        DataInputStream din = new DataInputStream(new FileInputStream(file));
        DataOutputStream dout = new DataOutputStream(new FileOutputStream(copy));
        byte c;
        c = 1;
        long time = System.currentTimeMillis();
        while(c!=-1)
        {
            c =  (byte) din.read();
            dout.write(c);
        }

        time = System.currentTimeMillis() - time;
        System.out.println(time);
    }
}

However i am not getting th expected result. As i know read() method DataInputStream reads next byte from input stream and converts it into int. Here i am converting that again into bytes and writing that byte to another file, but still this is not working as expected. The original file which i am trying to copy is of size 8.5 MB while the copied one has the size of 5.3 MB only.

Plz help me understand why this is happening.

Thanks in advance, Nishant


Solution

  • The read method returns an integer and not a byte.

    Reads the next byte of data from the input stream. The value byte is returned as an int in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned.

    So you would get an int, check if the value is not -1, and convert that back to byte to write it to the outputstream.

    int c = -1; 
    while((c =  din.read()) !=-1)
    {
      dout.write((byte)c);
    }
    

    As i know read() method DataInputStream reads next byte from input stream and converts it into int.

    Yes. so it should be int c; and not byte c;

    Here i am converting that again into bytes and writing that byte to another file

    So, this was your mistake. converting a byte to again a byte.

    The original file which i am trying to copy is of size 8.5 MB while the copied one has the size of 5.3 MB only.

    As pointed out, a byte with value '-1' and not the End of file marker -1, was read/encountered. It was returned as an integer of value '255' by the read() method. Your code stored it as '-1' byte in 'c',causing the while(c!=-1) check to fail and terminating halfway through.