java - 使用 DataInputStream 逐字节复制文件在完成之前停止

标签 java io inputstream

我用java编写了以下程序来使用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);
    }
}

但是我没有得到预期的结果。据我所知,read()方法DataInputStream从输入流中读取下一个字节并将其转换为int。在这里,我再次将其转换为字节并将该字节写入另一个文件,但这仍然无法按预期工作。我尝试复制的原始文件大小为 8.5 MB,而复制的文件大小仅为 5.3 MB。

请帮助我理解为什么会发生这种情况。

提前致谢, 尼尚特

最佳答案

read 方法返回一个整数而不是一个字节。

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.

因此,您将获得一个 int,检查该值是否不为 -1,然后将其转换回字节以将其写入输出流。

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.

是的。所以它应该是 int c; 而不是 byte c;

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

所以,这是你的错误。将字节再次转换为字节

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.

正如所指出的,一个字节,其值为'-1'并且不是文件结束标记-1,被读取/遇到。 它由 read() 方法以整数值 '255' 返回。 您的代码将其存储为 'c' 中的 '-1' 字节,导致 while(c!=-1) 检查失败并且中途终止。

关于java - 使用 DataInputStream 逐字节复制文件在完成之前停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26082719/

相关文章:

java vs scala - 在单独的线程上读取文件

java - 如何在不使用 `ScheduledThreadPoolExecutor` 的情况下使用单线程创建 `Executors.newSingleThreadScheduledExecutor` ?

java - 将 XML 元素动态插入文本节点

java - 如何将选定行的值替换为现有文件java

c - 将文本文件读取到双向链表

Java "File"有效,但 "InputStream"无效

java - 如何使用已在另一个 .xml 文件中配置的 bean?

java - 在 JUnit 测试中强制 SimpleFileVisitor 失败

java - Java InputStream函数 `available()`如何用C语言实现?

java - 正确重新组装拆分文件