我使用的緩衝筆者嘗試輸入文本到記事本,這是我來什麼碼了文本,輸入文本到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中的文本被新輸入的文本替換。
因爲您不應該創建一個新的Writer來覆蓋用戶輸入的每一行文件。您可以將寫入器配置爲附加文件。但即便如此,您也應該保持作家和媒體流暢通,直到用戶選擇不繼續。 –