How do i write to a text file WITHOUT deleting the current information in it? basically write on the next available line.

Dani AI

Generated

: the right idea is to open the file in append mode rather than overwriting it. pointed to the API and showed the common FileWriter + BufferedWriter pattern. A few practical, evergreen notes that add to those posts:

  • Prefer the java.nio.file API when possible: it lets the code specify create/append options and an explicit charset. It also mixes nicely with try-with-resources so files are closed reliably (Files API, StandardOpenOption).
  • Append will not add a newline automatically. If each entry should be on its own line, write an explicit newline after the text.
  • Do not swallow IOExceptions like in an empty catch block. Log or rethrow so failures are detectable.
  • For concurrent writes from multiple threads/processes, plain appends can interleave; use a file lock (FileChannel) or, better, a logging framework if this is a logging use case (FileChannel, Java logging guide).

Example approaches and options are documented in the Files class. Also consider calling Files.createDirectories(...) on the parent path first if the containing folder may not exist.

Recommended Answers

All 2 Replies

That sounds like you want to APPEND to the end of the current file.
Read the API doc for the file output classes. One of the constructors takes a boolean specifying whether to append or not.

try {
    BufferedWriter out = new BufferedWriter(new FileWriter("example.txt", true));
    out.write("aString");
    out.close();
} catch (IOException e) {
}

Just make sure "true" is the 2nd argument, it says to append or not.

Hope this helps!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.