2015-07-13 147 views
2

如何使用FileWriter和PrintWriter在文本文件中的特定行上書寫?我不想每次都要創建一個新文件。如何使用Java替換文件中的特定行?

編輯:我可以在文件中循環,在指定的行號處獲取字符串的長度,然後使用該長度在我到達該行時退格(刪除字符串),然後寫入新數據?

public static void setVariable(int lineNumber, String data) { 
    try { 
     // Creates FileWriter. Append is on. 
     FileWriter fw = new FileWriter("data.txt", true);  

     PrintWriter pw = new PrintWriter(fw);  

     //cycles through file until line designated to be rewritten is reached 
     for (int i = 1; i <= lineNumber; i++) {  
      //TODO: need to figure out how to change the append to false to overwrite data 
      if (i == lineNumber) { 
       pw.println(data); 
       pw.close(); 
      } else {   
       // moves printwriter focus to next line (doesn't overwrite) 
       pw.println(""); 
      } 
     } 
    } 
} 
+0

也許這個答案會有幫助? http://stackoverflow.com/a/6477893/1797341 –

回答

2

如果您使用的是Java 7或更高版本,如果lineNumber開始於1,你可以做到以下幾點:

public static void setVariable(int lineNumber, String data) throws IOException { 
    Path path = Paths.get("data.txt"); 
    List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8); 
    lines.set(lineNumber - 1, data); 
    Files.write(path, lines, StandardCharsets.UTF_8); 
} 

顯然,如果lineNumber開始於0,則:

lines.set(lineNumber, data); 
+0

這將工作與任何線?例如。我在文件中有90行,我想寫在第34位。 –

+0

你好,@TelleMiller :) * Yup *。它應該工作。 –

+0

我是否導入java.awt.List或java.util.List? –

相關問題