【问题标题】:Is there a way to append user input text to a file untill an exit character without appending the exit character in JAVA?有没有办法将用户输入文本附加到文件中,直到退出字符而不在 JAVA 中附加退出字符?
【发布时间】:2020-12-11 01:29:45
【问题描述】:

您好,我正在尝试将用户输入附加到文件中,直到用户输入退出字符。我已经达到了一定程度,但我遇到的问题是退出字符也附加在文本文件中。 以下是有关该问题的一些代码。 提前致谢。

public class Main {

public static void main(String[] args) throws IOException {

    BufferedWriter writer = null;
    BufferedReader reader = null;

    try {
        writer = new BufferedWriter(new FileWriter("C:\\Users\\gg\\newfile.txt",true));
        Scanner input = new Scanner(System.in);
        System.out.println("Enter text to enter file: ");
        //String text = input.nextLine();
        String text = "";
        while(!text.equals("/")){
            text = input.nextLine();
            writer.write(text);
            writer.newLine();
        }

    } catch (IOException e) {
        e.printStackTrace();
    }
    writer.close();
}

}

【问题讨论】:

    标签: java file append


    【解决方案1】:

    您可以将对 writer.write();writer.newLine() 的调用包装在一个 if 子句中,该子句检查文本是否等于退出字符以避免将其附加到文件中。

    顺便说一下,在比较固定字符串和 String 类型的变量时,字符串比较应该反过来进行。在固定字符串上调用 equals 并将变量作为 equals() 的参数传递。这是因为变量可能为 null,然后它会触发 NullPointerException。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-19
      • 1970-01-01
      • 2011-02-14
      • 1970-01-01
      • 2022-01-13
      • 1970-01-01
      • 2023-01-11
      • 2014-02-25
      相关资源
      最近更新 更多