user4486171
user4486171

Reputation:

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?

Upvotes: 4

Views: 9157

Answers (4)

Akvel
Akvel

Reputation: 951

You could use IOUtils from apatch-commons library

I think copyLarge fucntion it that you need

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500145

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.

Upvotes: 10

shikjohari
shikjohari

Reputation: 2288

you need to close your FileOutputStream and FileInputStream

Also you can use FileChannel to copy like as follows

FileChannel from = new FileInputStream(sourceFile).getChannel();
FileChanngel to = new FileOutputStream(destFile).getChannel();
to.transferFrom(from, 0, from.size());
from.close();
to.close();

Upvotes: 2

Steffen
Steffen

Reputation: 341

If you are using Java 8 try the Files.copy(Path source, Path target) method.

Upvotes: 2

Related Questions