Because the last fin.read()
will not read anything. According to JavaDoc it will return -1
, because of this your fout.write(i)
will write that -1
. You would do something like this, to correct this behavior:
do {
i = fin.read();
if (i>-1) //note the extra line
fout.write(i);
} while (i != -1);
Or change the do .. while
into a while .. do
call.
I suggest you should also look at the new NIO
API that will perform much better then transferring one character at a time.
File sourceFile = new File("C:/Users/NetBeansProjects/QuestionOne/input.txt");
File destFile = new File("C:/Users/NetBeansProjects/QuestionOne/output.txt");
FileChannel source = null;
FileChannel destination = null;
try {
if (!destFile.exists()) {
destFile.createNewFile();
}
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
destination.transferFrom(source, 0, source.size());
} catch (IOException e) {
System.err.println("Error while trying to transfer content");
//e.printStackTrace();
} finally {
try{
if (source != null)
source.close();
if (destination != null)
destination.close();
}catch(IOException e){
System.err.println("Not able to close the channels");
//e.printStackTrace();
}
}