【问题标题】:Why BufferedWriter doesn' write all lines in file?为什么 BufferedWriter 不会在文件中写入所有行?
【发布时间】:2023-03-14 09:35:01
【问题描述】:

这是我的代码。如果我输入 3 行文本然后键入“exit”,它将仅写入文件的最后一行文本。 我错过了什么? 谢谢。

`public class WriteFile {
    public static void writeFile() throws IOException {
        Scanner sc = new Scanner(System.in);
        String text;
        File file = new File("file.txt");
        BufferedWriter out = new BufferedWriter(new FileWriter(file));
        while (!sc.nextLine().equalsIgnoreCase("exit")) {
                text = sc.nextLine();
                out.write(text);
                out.newLine();

            }
        sc.close();
        out.flush();
        out.close();
    }
}`

【问题讨论】:

    标签: bufferedwriter writetofile


    【解决方案1】:

    是的,你应该使用 append() 方法,写删除最后插入的文本:

    public static void writeFile() throws IOException {
            Scanner sc = new Scanner(System.in);
            String text = "";
            File file = new File("file.txt");
            BufferedWriter out = new BufferedWriter(new FileWriter(file));
            while (!(text = sc.nextLine()).equalsIgnoreCase("exit")) {
                out.append(text);
                out.newLine();
            }
            sc.close();
            out.flush();
            out.close();
        }
    

    【讨论】:

    • 我测试了这段代码,它运行良好,你为什么说它不工作?你有什么结果?你有错误吗?
    猜你喜欢
    • 2014-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多