Is there a way to append user input text to a file untill an exit character without appending the exit character in JAVA?

huangapple go评论84阅读模式
英文:

Is there a way to append user input text to a file untill an exit character without appending the exit character in JAVA?

问题

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 = "";
            while (!text.equals("/")) {
                text = input.nextLine();
                writer.write(text);
                writer.newLine();
            }

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

Hello I am trying to append user input to a file untill the user enters an exit character. I have reached to a certain point but the problem i have is that the exit character also gets appended in the text file.
Below is some code concerning the issue.
Thanks in advance.

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();
}

}

答案1

得分: 0

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

顺便说一下,进行字符串比较时,应该以另一种方式进行,即用一个固定的字符串与类型为 String 的变量进行比较,应该调用固定字符串上的 equals 方法,并将变量作为 equals() 的参数传递进去。这是因为该变量可能为 null,那样的话就会触发 NullPointerException。

英文:

You can wrap the calls to writer.write(); and writer.newLine() in an if clause that checks whether text is equal to the exit character to avoid it being appended to the file.

By the way, string comparisons where you compare a fixed string with a variable of type String should be done the other way around. Call equals on the fixed string and pass the variable as an argument of equals(). This is because the variable could be null, and then it would trigger a NullPointerException.

huangapple
  • 本文由 发表于 2020年8月22日 00:26:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/63526623.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定