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.
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);
}
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() );
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With