【问题标题】:Inputting a text into file.txt without replacing the text when in loop [duplicate]在循环中将文本输入file.txt而不替换文本[重复]
【发布时间】:2017-08-03 08:40:51
【问题描述】:

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

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。您可以配置编写器以附加文件。但即便如此,您也应该让编写器和流保持打开状态,直到用户选择不继续。

标签: java do-while bufferedwriter


【解决方案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 + "'");
    }
}

【讨论】:

  • 可能还值得补充一点,将扫描仪放在 try-with-resources 中意味着 System.in 也将在块的末尾关闭。这没关系,因为块的末尾在 main() 的末尾。但是如果你想在块之后做任何进一步的输入,你必须把扫描仪从 try-with-resources 中取出。
【解决方案2】:

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

【讨论】:

  • 嘿,谢谢...它正在工作
猜你喜欢
  • 1970-01-01
  • 2016-04-26
  • 1970-01-01
  • 2013-08-26
  • 2014-06-03
  • 2012-03-05
  • 1970-01-01
  • 2018-02-06
  • 1970-01-01
相关资源
最近更新 更多