简体   繁体   English

需要停止txt文件中的单词覆盖JAVA

[英]Need to stop words in txt file overwriting JAVA

Hi im trying to create a word list using a .txt file where i take input off the user from a JOptionPane window and it stores it on a new line of the text file. 嗨,我尝试使用.txt文件创建单词列表,在此我从JOptionPane窗口中删除了用户的输入,并将其存储在文本文件的新行中。 the problem I'm having is that when I input more than one word it overwrites the data that is already there. 我遇到的问题是,当我输入多个单词时,它会覆盖已经存在的数据。 I want it to skip a line and add it onto the current list. 我希望它跳过一行并将其添加到当前列表中。 This is the code I have: 这是我的代码:

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();
}

just put true at the end of the filewriter makes it switch to append mode: 只需在文件编写器的末尾设置为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) {
         }
      }
}

The problem is that you are closing the stream at the end of the method. 问题是您要在方法结束时关闭流。 Each time you call it, it is going to recreate the FileWriter and the PrintWriter, take the input, add it to the file, and then close it again. 每次调用它时,它将重新创建FileWriter和PrintWriter,获取输入,将其添加到文件中,然后再次关闭它。 One way around this might be to create a static String object, and add the user input to it each time. 解决此问题的一种方法可能是创建一个静态String对象,并每次将用户输入添加到该对象。 At the end of the program, write that string to the file and then close it. 在程序末尾,将该字符串写入文件,然后关闭它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM