在循环中输入文本到file.txt而不替换文本

时间:2017-08-03 08:40:51

标签: java do-while bufferedwriter

我正在尝试使用缓冲编写器将文本输入到记事本中,这就是我提出的代码,

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"));


}
}

所以问题是当用户想要继续并再次输入文本并完成整个过程时,文件中的文本将被新输入的文本替换。

2 个答案:

答案 0 :(得分:1)

您的问题只是您在覆盖模式下打开fileWriter,使其只需将新文本附加到现有文件,只需将new FileWriter(fn)替换为FileWriter(fn,true)即可修复它

但是,我也注意到你对资源的处理不当(在我看来),所以我建议你打开Streams / Reader / Writer一次,然后关闭它们最后:

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 + "'");
    }
}

答案 1 :(得分:0)

只需添加FileWriter(fn,true),即可保留现有内容,并将新内容附加到文件末尾。