December 7, 2023

How to append text to a file in Java

This article shows how to use the following Java APIs to append text to the end of a file. (1) Files.write – Append a single line to a file, Java 7. (2) Files.write – Append multiple lines to a file, Java 7, Java 8. (3) Files.writeString – Java 11. (4) FileWriter, (5) FileOutputStreamFileUtils – Apache Commons IO. In Java, for NIO APIs like Files.write, we can use StandardOpenOption.APPEND to enable the append mode. For classic IO APIs like FileWriter or FileOutputStream, we can pass a true to the constructor’s second argument to enable the append mode.

How to append text to a file in Java Read More

Java create and write to a file

In Java, we can use Files.write to create and write to a file. The Files.write also accepts an Iterable interface; it means this API can write a List to a file. Before Java 7, for writing bytes (image) to a file, we use FileOutputStream; for writing characters (text) to a file, we use FileWriter, and usually wrapped by a BufferedWriter to gain performance. In Java 7, there is a new NIO class named java.nio.file.Files, and we can use Files.write() to write both bytes and characters. In Java 8, we can use Files.newBufferedWriter(path) to create a BufferedWriter. In Java 11, there is a new Files.writeString API to write string directly to a file.

Java create and write to a file Read More

Java Core Tutorials

A series of Java 8 up to date tips and examples, hope you like it. Java 11 reached General Availability on 25 September 2018, this is a Long Term Support (LTS) version. Java 12 reached General Availability on 19 March 2019. Java 13 reached General Availability on 17 September 2019. Java 14 reached General Availability on 17 March 2020. Java 15 reached General Availability on 15 September 2020. Java 16 reached General Availability on 16 March 2021. Java 17 is a long-term support (LTS) release, reached General Availability on 14 September 2021.

Java Core Tutorials Read More

How to read a file in Java

This article focus on a few of the commonly used methods to read a file in Java. 1 – Files.lines, return a Stream (Java 8), 2 – Files.readString, returns a String (Java 11), max file size 2G. 3 – Files.readAllBytes, returns a byte[] (Java 7), max file size 2G. 4 – Files.readAllLines, returns a List (Java 8) . 5 – BufferedReader, a classic old friend (Java 1.1 -> forever) . 6 – Scanner (Java 1.5)

How to read a file in Java Read More