Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying files in java

Would you please tell me why does this character " ÿ " appears at the end of my output file. (I use try/catch)

        File f1 = new File("C:/Users/NetBeansProjects/QuestionOne/input.txt");
        File f2 = new File("C:/Users/NetBeansProjects/QuestionOne/output.txt");
        fin = new FileInputStream(f1);
        fout = new FileOutputStream(f2);

        do {
            i = fin.read();
            fout.write(i);

        } while (i != -1);

The code copies the file content but it ends it with this strange character. Do I have to include the entire code?

Thanks.

like image 387
InspiringProgramming Avatar asked Nov 28 '22 08:11

InspiringProgramming


2 Answers

The method fin.read() returns -1 when there's nothing left to read; but you're actually writing that -1 to fout, even though it didn't occur in fin. It shows up as that ÿ character.

One way to write your loop to avoid this problem is

    while((i = fin.read()) != -1 ){
        fout.write(i);
    } 
like image 153
Dawood ibn Kareem Avatar answered Dec 04 '22 17:12

Dawood ibn Kareem


try to use the new Files class introduced in Java 7

public static void copyFile( File from, File to ) throws IOException {
    Files.copy( from.toPath(), to.toPath() );
}
like image 27
Simon Avatar answered Dec 04 '22 17:12

Simon