如何使用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("");
}
}
}
}
也許這個答案會有幫助? http://stackoverflow.com/a/6477893/1797341 –