您好,我正在尝试使用 .txt 文件创建单词列表,其中我从 JOptionPane 窗口获取用户输入,并将其存储在文本文件的新行中。我遇到的问题是,当我输入多个单词时,它会覆盖已经存在的数据。我希望它跳过一行并将其添加到当前列表中。这是我的代码:
public static void Option1Method() throws IOException
{
FileWriter aFileWriter = new FileWriter("wordlist.txt");
PrintWriter out = new PrintWriter(aFileWriter);
String word = JOptionPane.showInputDialog(null,"Enter word or phrase: ");
out.println(word);
out.close();
aFileWriter.close();
}
最佳答案
只需将 true 放在文件写入器的末尾即可使其切换到追加模式:
public static void Option1Method(){
FileWriter aFileWriter = null;
PrintWriter out = null;
try {
aFileWriter = new FileWriter("wordlist.txt",true);
out = new PrintWriter(aFileWriter);
String word = JOptionPane.showInputDialog(null, "Enter word or phrase: ");
out.println(word);
} catch (IOException iOException) {
} catch (HeadlessException headlessException) {
} finally {
out.close();
try {
aFileWriter.close();
} catch (IOException iOException) {
}
}
}
关于java - 需要阻止txt文件中的单词覆盖JAVA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15601778/