Explain Codes LogoExplain Codes Logo

How to append text to an existing file in Java?

java
file-manipulation
bufferedwriter
printwriter
Anton ShumikhinbyAnton Shumikhin·Nov 25, 2024
TLDR

Easily append text to an existing file by employing FileWriter in append mode:

try (FileWriter fw = new FileWriter("file.txt", true)) { fw.write("Appended text"); // Add a "spice" of text to your file recipe } catch (IOException e) { // Robust error handling here. Don't let exceptions catch you unprepared! }

Setting the second argument of FileWriter to true kickstarts the append mode. Invoke write on FileWriter to append your text.

Optimize with BufferedWriter

Give your file manipulations a boost using BufferedWriter that provides an efficiency bonus for numerous write operations:

try (BufferedWriter bw = new BufferedWriter(new FileWriter("file.txt", true))) { bw.write("Appended text\n"); // Keep calm and carry on writing // Space for more writing operations } catch (IOException e) { // Error handling, because prevention is better than cure }

BufferedWriter becomes handy when you have tons of writing operations - call it bulk-processing of your text append operations.

Leverage PrintWriter

For a more fluent syntax, adopt PrintWriter, lighting up your code with a richer set of methods similar to System.out.print:

try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("file.txt", true)))) { out.println("Appended text"); // Adding another pearl to the string } catch (IOException e) { // Handle exceptions like a pro }

Unlock NIO.2 goodie bag

The NIO.2 package comes packed with Files and Paths classes, offering a modern and flexible alternative:

Path path = Paths.get("file.txt"); try { Files.write(path, Arrays.asList("Appended text"), StandardCharsets.UTF_8, StandardOpenOption.CREATE, StandardOpenOption.APPEND); } catch (IOException e) { // If it ain't broken, catch exceptions }

The CREATE attribute with Files.write will do the charm of manifesting the file if it's not already there, saving you from a FileNotFoundException.

Don't let encoding and safety slip

When you're in the realm of file manipulation, never overlook encodings and safety:

  • Explicitly state the character encoding (for example, StandardCharsets.UTF_8) to ensure text consistency across different environments.
Files.writeString(path, "Appended text", StandardOpenOption.APPEND, StandardCharsets.UTF_8);
  • Implement exception handling and handle resource management carefully, especially with older Java versions.
Writer writer = null; try { writer = new FileWriter("file.txt", true); writer.write("Appended text"); // Drawing on your file canvas } finally { if (writer != null) { writer.close(); // Shut the door when you leave! } }

Third-party libraries to the rescue

Libraries like Apache's FileUtils can simplify text appending:

try { FileUtils.writeStringToFile(new File("file.txt"), "Appended text", Charset.defaultCharset(), true); } catch (IOException e) { // Exception handling, covering your back }

Let FileUtils know that you're appending, not overwriting, by using true as the last argument.

Before making your mark, ensure you're planted firmly in your directories:

Files.createDirectories(path.getParent()); // Ensuring you know where your files hangout

This step guarantees that all parent directories are ready and set before you write the file, evading potential application crashes.