One of the common task related to a text file is to append or add some contents to the file. It’s really simple to do this in Java using a FileWriter
class. This class has a constructor that accept a boolean parameter call append
. By setting this value to true
a new data will be appended at the end of the file when we write a new data to it.
Let’s see an example.
package org.kodejava.io;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class AppendFileExample {
public static void main(String[] args) {
File file = new File("user.txt");
try (FileWriter writer = new FileWriter(file, true)) {
writer.write("username=kodejava;password=secret" + System.lineSeparator());
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024