2014-01-17 118 views
1

當我運行的代碼一切正常,但內容不寫入target.txt。請告訴我爲什麼下面的代碼不工作?

public class SrtExtractor { 
     public static void main(String[] args) throws IOException { 
      Path source = Paths.get("files/loremipsum.txt"); 
      Path target = Paths.get("files/target.txt"); 
      Charset charSet = Charset.forName("US-ASCII"); 
      BufferedReader reader = Files.newBufferedReader(source, charSet); 
      BufferedWriter writer = Files.newBufferedWriter(target, charSet); 
      String temp; 
      ArrayList<String> list = new ArrayList<>(); 
      while((temp = reader.readLine())!=null){ 
       list.add(temp); 
       System.out.println(temp); 
      } 
      for(int i = 0; i<list.size(); i++) 
      { 
       writer.append(list.get(i));//why this line is not working??? 
      } 
     } 
    } 
+1

嘗試writer.flush()和writer.close() – Gus

+1

您離開'writer.close()'。 – PeterMmm

+0

你有沒有費心去瀏覽調試器中的代碼? – OldProgrammer

回答

1
for(int i = 0; i<list.size(); i++) { 
    writer.append(list.get(i)); 
} 
writer.close(); //Add this 
reader.close(); //Add this 

您還沒有表明你做寫入文件。直到你說close()該文件實際上並未被寫入,文本只是坐在BufferedWriter

0

大家都說,你應該加writer.close()

到另一邊,我認爲要在一個文本文件中寫的最好的方式是這樣的(它總是對我來說運行):

File file = new File(path); 
FileOutputStream fout = new FileOutputStream(file); 
OutputStreamWriter osw = new OutputStreamWriter(fout); 
Writer w = new BufferedWriter(osw); 
for(...){ 
    w.write(...); 
} 
3

您使用的是BufferedWriter類 - 在這種情況下,你寫的內容仍然在Buffer中。需要調用writer.flush();來清除Buffer的內容並將它們寫入基礎流。

flush()當調用close()時也會自動調用。爲了避免內存泄漏,當程序完成其資源時應該調用close()。正確關閉資源很難做到正確,但Java 7添加了新的try-with-resources construct以幫助程序員正確關閉資源。

下面是您重寫爲使用try-with-resources構造的示例。這將確保您的兩個流都能正確關閉,即使在處理文件時發生異常也是如此。它基本上與您的讀寫器上調用close()相同,但它更安全並使用更少的代碼。

public class SRTExtractor { 
    public static void main(String[] args) throws IOException { 
     Path source = Paths.get("files/loremipsum.txt"); 
     Path target = Paths.get("files/target.txt"); 
     Charset charSet = Charset.forName("US-ASCII"); 
     try (
      BufferedReader reader = Files.newBufferedReader(source, charSet); 
      BufferedWriter writer = Files.newBufferedWriter(target, charSet); 
     ) { 
      String temp; 
      ArrayList<String> list = new ArrayList<>(); 
      while ((temp = reader.readLine()) != null) { 
       list.add(temp); 
       System.out.println(temp); 
      } 
      for (int i = 0; i < list.size(); i++) { 
       writer.append(list.get(i)); 
      } 
     } 
    } 
} 
+0

+1以前沒見過自動關閉資源的新功能,真好! – Fredrik

相關問題