java - 需要阻止txt文件中的单词覆盖JAVA

标签 java file text joptionpane

您好,我正在尝试使用 .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/

相关文章:

linux - 从 tar 归档 Linux 中提取前 10 个最大的文件

file - 在运行时加载资源文件

java - 有没有办法让需要文件参数的命令行程序使用标准输入?

javascript - 在 jQuery 中双击禁用文本突出显示

java - Struts 2 避免重复 Action

java - 使用gradle,错误: cannot find symbol @Test

文本值包含\0(反斜杠 0)的 Postgresql COPY

python - 为 turtle 构建内置文本字段,while 语句不起作用

java - 为什么下面的示例中 ArrayList 没有更新?

java - 如何将 Java 属性序列化为 JSON