Java is trying to add text to a file that already exists

Asked 2 years ago, Updated 2 years ago, 119 views

Java is trying to add text to a file that already exists What should I do?

java file-io io text-file

2022-09-22 16:56

1 Answers

It's easy to use the Files class.

try {
    Files.write(Paths.get("myfile.txt"), "the text".getBytes(), StandardOpenOption.APPEND);
}catch (IOException e) {
    //exception handling left as an exercise for the reader
}

But if you write the same file several times, it's slow because you open it, close it, and do it a lot.

try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("myfile.txt", true)))) {
    out.println("the text");
    //more code
    out.println("more text");
    //more code
}catch (IOException e) {
    //exception handling left as an exercise for the reader
}

Do it like this.

The second factor in FileWriter is whether to add it to the file. If you are going to use it several times, I recommend BufferedWriter. PrintWriter gives println access, which is the same as System.out.

try { PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("myfile.txt", true))); out.println("the text"); out.close(); } } catch (IOException e) { //exception handling left as an exercise for the reader }


2022-09-22 16:56

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.