How to write to a file in Java


Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content
// {...}
Path file = Paths.get("file.txt");
// Method 1: small files: write raw bytes
byte[] bytes = "1st line\n".getBytes();
Files.write(file, bytes);
// Method 2: small files: write lines
List<String> lines = Arrays.asList(
"2nd line",
"3rd line",
"4th line"
Files.write(file, lines, APPEND); // UTF8 by default
// Method 3: big files: write text
try (BufferedWriter writer = Files.newBufferedWriter(file, APPEND)) {
String line = "5th line";
writer.write(line, 0, line.length());
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content