Back
Close

How to write to a file in Java

[CG]BOUGA
2,334 views
// {...}
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());
writer.newLine();
}
//{...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants