3

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

这是我的代码:

   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

4 回答 4

9

这是错误:

bos.write(buffer);

您正在写出整个缓冲区,即使您只将数据读入其中的一部分。你应该使用:

bos.write(buffer, 0, numBytes);

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

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

于 2015-01-23T10:27:46.507 回答
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();
于 2015-01-23T10:27:56.793 回答
2

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

于 2015-01-23T10:23:50.770 回答
0

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

我认为您需要的 copyLarge 功能

于 2015-01-23T10:33:27.753 回答