如何通过bufferedInputStream和bufferedOutputStream复制JAVA中的文件?

时间:2015-01-23 10:21:00

标签: java eof bufferedinputstream bufferedoutputstream

我想使用bufferedInputStreambufferedOutputStream将大型二进制文件从源文件复制到目标文件。

这是我的代码:

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

我可以成功复制但是我使用

cmp src dest

在命令行中比较两个文件。 错误消息

  

cmp:文件上的EOF

出现。我可以知道我哪里错了吗?

4 个答案:

答案 0 :(得分:8)

这是错误的:

bos.write(buffer);

您正在写出整个缓冲区,即使您只将数据读入 part 。你应该使用:

bos.write(buffer, 0, numBytes);

如果您使用的是Java 7或更高版本,我还建议使用try-with-resources,否则将close调用放在finally块中。

正如Steffen所说,Files.copy是一种更简单的方法,如果您可以使用的话。

答案 1 :(得分:2)

您需要关闭FileOutputStreamFileInputStream

您也可以使用FileChannel进行复制,如下所示

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

答案 2 :(得分:1)

如果您使用的是Java 8,请尝试Files.copy(Path source, Path target)方法。

答案 3 :(得分:0)

您可以使用apache-commons库中的IOUtils

我认为copyLarge是你需要的功能