How to copy files in JAVA by bufferedInputStream and bufferedOutputStream?

I would like to use bufferedInputStream and bufferedOutputStream to copy large binary files from source file to destination file.

Here 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 successfully copy but then I use

cmp src dest

in the command line to compare two files. The error message

cmp: EOF on files

appears. May I know where I was wrong?

Jon Skeet
people
quotationmark

This is the mistake:

bos.write(buffer);

You're writing out the whole buffer, even if you only read data into part of it. You should use:

bos.write(buffer, 0, numBytes);

I'd also suggest using try-with-resources if you're using Java 7 or later, or put the close calls in a finally block otherwise.

As Steffen notes, Files.copy is a simpler approach if that's available to you.

people

See more on this question at Stackoverflow