我對Java相當陌生。如果它不存在,我試圖將「List:」添加到新文本文件的開頭。相反,文本文件是空白的,輸入下面是一行空格。Filewriter不會將文本追加到新創建的文件
File hi = new File("hi.txt");
try{
if(!hi.exists()){
System.out.printf("\nCreating 'hi.txt'.");
hi.createNewFile();
String hello = "List:";
new FileWriter(hi).append(hello);
}
else{
System.out.printf("\nWriting to 'hi.txt'");
}
FileWriter writeHere = new FileWriter(hi, true);
String uling = "hi";
writeHere.append(uling);
writeHere.close();
}
//error catching
catch(IOException e){
System.out.printf("\nError. Check the file 'hi.txt'.");}
你記得關閉FileWriter嗎? – immibis 2015-03-19 09:16:49
FileWriter需要第二個參數來啓用'append'模式,請參閱:http://stackoverflow.com/questions/1225146/java-filewriter-with-append-mode – steenbergh 2015-03-19 09:18:06
@immibis:'writeHere.close()'存在在示例代碼中 - 雖然承認使用try-with-resources塊會更好。 – 2015-03-19 09:18:49