2017-08-03 30 views
0

我使用的緩衝筆者嘗試輸入文本到記事本,這是我來什麼碼了文本,輸入文本到file.txt的,無需更換時,在環

import java.util.Scanner; 
import java.io.*; 
public class FileSample { 
    public static void main (String[] args) { 
    Scanner sc = new Scanner(System.in); 
    String yourtext = " "; 
    String fn = "file.txt"; 
    String choice = " "; 
    do{ 
    try{ 
     FileWriter fw = new FileWriter(fn); 
     BufferedWriter bw = new BufferedWriter(fw); 
     System.out.print("Enter text: "); 
     yourtext = sc.nextLine(); 
     bw.write(yourtext); 
     bw.newLine(); 

     bw.close(); 
     System.out.println("==================================="); 
     System.out.print("Do you still want to continue?:\n [Y]Yes \n [N]No 
     \n::"); 
     choice = sc.nextLine(); 
    }catch(IOException ex){ 
     System.out.println("Error writing to file '" + fn + "'"); 
    } 
    }while(choice.equalsIgnoreCase("Y")); 


} 
} 

所以問題是當用戶想要繼續並再次輸入文本並完成該過程時,應該在file.txt中的文本被新輸入的文本替換。

+0

因爲您不應該創建一個新的Writer來覆蓋用戶輸入的每一行文件。您可以將寫入器配置爲附加文件。但即便如此,您也應該保持作家和媒體流暢通,直到用戶選擇不繼續。 –

回答

0

只需添加FileWriter(fn,true)這將保留現有內容並將新內容附加到文件末尾。

+1

嘿,謝謝......它現在正在工作 – Pon

1

你的問題是,你只是在覆蓋模式下打開fileWriter,以使其只需將新文本附加到現有文件,只需將new FileWriter(fn)替換爲FileWriter(fn,true)即可解決該問題。

但是,我也注意到,你的排序處理不當的資源(在我看來),所以我建議你一旦打開流/讀/寫,並在年底關閉它們:

public static void main(String[] args) { 
    String yourtext = " "; 
    String fn = "file.txt"; 
    String choice = " "; 
    try (Scanner sc = new Scanner(System.in); 
      FileWriter fw = new FileWriter(fn);   // making sure to free resources after using them 
      BufferedWriter bw = new BufferedWriter(fw);) { 
     do { 
      System.out.print("Enter text: "); 
      yourtext = sc.nextLine(); 
      bw.write(yourtext); 
      bw.newLine(); 
      System.out.println("==================================="); 
      System.out.print("Do you still want to continue?:\n [Y]Yes \n [N]No \n::"); 
      choice = sc.nextLine(); 
     } while (choice.equalsIgnoreCase("Y")); 
    } catch (IOException ex) { 
     System.out.println("Error writing to file '" + fn + "'"); 
    } 
} 
+0

值得一提的是,讓掃描儀在資源嘗試中意味着System.in也將在塊的結尾處關閉。這是可以的,因爲塊的結尾位於main()的末尾。但是如果你想在塊之後進行任何進一步的輸入,你將不得不將掃描儀帶出資源試用版。 –