2015-03-19 57 views
0

我對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'.");} 
+2

你記得關閉FileWriter嗎? – immibis 2015-03-19 09:16:49

+0

FileWriter需要第二個參數來啓用'append'模式,請參閱:http://stackoverflow.com/questions/1225146/java-filewriter-with-append-mode – steenbergh 2015-03-19 09:18:06

+0

@immibis:'writeHere.close()'存在在示例代碼中 - 雖然承認使用try-with-resources塊會更好。 – 2015-03-19 09:18:49

回答

0

傳遞true作爲第二個參數的FileWriter打開「追加」模式(在你創建的第一個FileWriter的)。

另外,您應該創建變量FileWriter,並在追加「List:」後關閉它,因爲您離開該變量的範圍。在線7-9修改:

所以,我編輯的代碼如下:

File hi = new File("hi.txt"); 
try { 
    if (!hi.exists()) { 
     System.out.printf("\nCreating 'hi.txt'."); 
     hi.createNewFile(); 
     String hello = "List:"; 
     FileWriter writer = new FileWriter(hi, true); 
     writer.append(hello); 
     writer.close(); 
    } 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'."); 
} 

通知。

http://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html

+0

你的意思是像'FileWriter writeHere = new FileWriter(hi,true);'在示例代碼中? – 2015-03-19 09:17:49

+0

@JonSkeet不,我的意思是上面幾行 - 史蒂夫試圖追加「列表:」。 – 2015-03-19 09:18:54

+0

謝謝!它解決了這個問題。只是一個簡單的問題,爲什麼在每一次寫入之後,文件編寫者總是會關閉?我得到了需要關閉它,但爲什麼在所有寫入完成後關閉它? – Steve 2015-03-19 09:31:21

3

問題是這一行:

new FileWriter(hi).append(hello); 

你不關閉的作家,這意味着:

  • 的文件句柄可能仍處於打開狀態,這可能當您嘗試寫入時會導致問題
  • 您不是沖水作家,所以輸入可能會丟失

您應該養成使用try-with-resources獲取並自動關閉寫入程序的習慣,即使發生異常。

就個人而言,我會改變你的代碼的結構有點所以你只打開文件一次:

File hi = new File("hi.txt"); 
boolean newFile = !hi.exists(); 
System.out.printf("%n%s 'hi.txt'.", newFile ? "Creating" : "Writing to"); 
try (Writer writer = new FileWriter(hi, true)) { 
    // Note: if you've already got a string, you might as well use write... 
    if (newFile) { 
     writer.write("List:"); 
    } 
    writer.write(uling); 
} 
catch(IOException e) { 
    System.out.printf("\nError. Check the file 'hi.txt'."); 
} 
0

不要忘記關閉編寫這是非常重要的。那麼,如果你不關閉它,它將不會被寫入。

writer.close()。