In this source code example, we show you how to append a string to an existing file in Java.
We use write() method from java.nio.file.Files class to append data to a file.
Java Append to File Example
This example appends data with Files.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
public class JavaAppendFileFiles {
public static void main(String[] args) throws IOException {
String fileName = "src/main/resources/sample.txt";
byte[] tb = "appending some string\n".getBytes();
Files.write(Paths.get(fileName), tb, StandardOpenOption.APPEND);
}
}
The third parameter of Files.write() tells how the file was opened for writing. With the StandardOpenOption.APPEND, the file was opened for appending.
Files.write(Paths.get(fileName), tb, StandardOpenOption.APPEND);
References
Related Java NIO Files Examples
- Java File Copy Example
- Java Create File Example
- Java Delete File Example
- Java File Size Example
- Java Get File Owner Example
- Java File Move Example
- Java Read File Example
- Java Write File Example
- Java Create Directory Example
- Java Create Multiple Directories Example
- Java List All Subdirectories From a Directory Example
- Java Append to File Example
Comments
Post a Comment