简体   繁体   English

FileInputStream.read()与FileOutputStream.write()

[英]FileInputStream.read() vs FileOutputStream.write()

I tried to make a simple program that copies a file. 我试图制作一个简单的程序来复制文件。 According to the documentation, FileInputStream.read() and FileOuputStream.write() seemed similar to me. 根据文档, FileInputStream.read()FileOuputStream.write()似乎与我相似。 They read and write an int , from and to a file, respectively. 他们分别从文件读取int和向文件写入int So then, why does the following not work? 那么,为什么下面的方法不起作用?

import java.io.*;

class CopyFile {
    public static void main(String[] args) throws IOException {
        FileInputStream original = new FileInputStream(args[0]);
        FileOutputStream copy = new FileOutputStream(args[1]);
        while (original.read() != -1) {
            copy.write(original.read());
        }
    }
}

The resulting file is totally different from the original. 生成的文件与原始文件完全不同。 Why isn't this working as I expected? 为什么这没有按我预期的那样工作?

Look at your code: 查看您的代码:

    while (original.read() != -1) {
        copy.write(original.read());
    }

You read one byte to test if it's end of file, then you read another byte to write. 您读取一个字节以测试它是否是文件结尾,然后读取另一个字节以进行写入。

Hence the byte you read in while condition is skipped. 因此,字节,你读while状态被跳过。

The correct way is: 正确的方法是:

    int b;
    while ((b=original.read()) != -1) {
        copy.write(b);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM