如何使 FileWriter 不会连续用输入替换第一行,而只是移动到下一行?

问题描述 投票:0回答:1

我正在使用 FileWriter,这样当用户回答问题时,链接的文本就会添加到附加的文本文件中,而不是每个 .write("");转到 txt 文件中的下一行,当我使用行分隔符或 ( )它只是在下面添加空行,同时继续替换第 1 行上的文本。

System.out.println("Please choose your sub size \n 1 - six inch ($7.19) \n 2 - twelve inch ($10.99) \n  Please enter '1' or '2'");
sub.size = input.nextLine();

// filtering all input other than '1' and '2'
while (!sub.size.equals("1") && !sub.size.equals("2")) {
    System.out.println("Please enter '1' or '2'");
    sub.size = input.nextLine();
}

//adding to the price depending on chosen size
if (sub.size.equals("1")) {
    sub.price = sub.price + 7.19;
    try {
        FileWriter orderTaker = new FileWriter("subOrder.txt");
        orderTaker.write("6 inch Sub");
        //orderTaker.write(System.lineSeparator());
        orderTaker.close();
    } catch(IOException e) {
        System.out.println("An error occurred.");
        e.printStackTrace();
    }
}

First input After second input

根据某人的建议尝试了 bufferedWriter,已经尝试过( ), 试过 ( ),尝试过 lineSeparator

java filewriter
1个回答
0
投票

问题的解决方案在于您正在使用的构造函数。如果您不想覆盖现有文件内容,则需要使用

FileWriter(File, boolean)
构造函数,该构造函数采用名为
append
的布尔参数。将append设置为true,它会将您的数据添加到文件末尾而不是覆盖它。

但是,更好的解决方案是保持 FileWriter 打开,直到收集完所有订单为止。重复打开和关闭文件句柄会导致性能下降。这是一个例子:

Scanner input = new Scanner(System.in);
boolean acceptingOrders = true;

try (FileWriter orderTaker = new FileWriter("subOrder.txt", true)) {
    while (acceptingOrders) {
        System.out.println("1 - six inch ($7.19)");
        System.out.println("2 - twelve inch ($10.99)");
        System.out.println("Please enter '1' or '2' or 'done'");

        boolean invalidInput = true;
        String userInput = input.nextLine();
        do {
            if (userInput.equals("1")) {
                sub.size = userInput;
                sub.price = sub.price + 7.19;
                orderTaker.write("6 inch Sub\n");

                invalidInput = false;
            } else if (userInput.equals("2")) {
                sub.size = userInput;
                sub.price = sub.price + 10.99;
                orderTaker.write("12 inch Sub\n");

                invalidInput = false;
            } else if (userInput.equalsIgnoreCase("done")) {
                acceptingOrders = false;
                invalidInput = false;
            } else {
                System.out.println("Please enter '1' or '2' or 'done'");
                userInput = input.nextLine();
            }
        } while (invalidInput);
    }
} catch (IOException e) {
    System.out.println("An error occurred.");
    e.printStackTrace();
}
© www.soinside.com 2019 - 2024. All rights reserved.