[英](re-writing the text file and keep previous data)get value and write in notepad/ms-word- every time in new line of notepad file
我知道如何從JTextField獲取值並將其寫入Java語言的文本文件中。 這是我的代碼:
public class createfile {
private Formatter x;
public void openFile() {
try {
x = new Formatter("c:\\definition.txt");
} catch (Exception e) {
System.out.println("Error");
}
}
private void addRecords() {
x.format(null, jTextField3);
}
public void closFile() {
x.close();
}
}
它可以正常工作,並將jTextField3的值寫入到名為“ definition.txt”的文件中。 但是,如果用戶再次運行該程序,並在jTextField3中輸入新值,則“ definition.txt”將填充新數據! 以前的數據將會丟失! 我不想那樣! 我想保留每次用戶輸入的所有數據。 我應該如何更改代碼? 謝謝 !
您想要附加到文件而不是覆蓋它。 采用文件名的Formatter
構造函數似乎無法勝任。 我建議您創建一個FileOutputStream
,在其中可以明確要求附加。 您可以將該流傳遞給Formatter
構造函數,而不是原始文件名。
x = new Formatter(new FileOutputStream("c:\\definition.txt", true));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.