簡體   English   中英

需要停止txt文件中的單詞覆蓋JAVA

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

嗨,我嘗試使用.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) {
         }
      }
}

問題是您要在方法結束時關閉流。 每次調用它時,它將重新創建FileWriter和PrintWriter,獲取輸入,將其添加到文件中,然后再次關閉它。 解決此問題的一種方法可能是創建一個靜態String對象,並每次將用戶輸入添加到該對象。 在程序末尾,將該字符串寫入文件,然后關閉它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM