因为最后fin.read()
不会读任何东西。根据JavaDoc,它会返回-1
,因此你fout.write(i)
会写那个-1
。你会做这样的事情来纠正这种行为:
do {
i = fin.read();
if (i>-1) //note the extra line
fout.write(i);
} while (i != -1);
或者改成do .. while
电话while .. do
。
我建议您还应该看看新的NIO
API,它的性能比一次传输一个字符要好得多。
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();
}
}