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 this -1 . You would do something similar to fix this behavior:
do { i = fin.read(); if (i>-1)
Or change do .. while to call while .. do .
I suggest you also look at the new NIO API, which will work much better than passing 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(); } }
source share