简体   繁体   中英

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. They read and write an int , from and to a file, respectively. 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.

The correct way is:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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