EN
Java - how to save String to file?
1 answers
10 points
What is the best way how to save simple String to file in java?
There is more then one way to do it, which one is the best?
1 answer
5 points
Quick solution:
xxxxxxxxxx
1
import java.io.BufferedWriter;
2
import java.io.IOException;
3
import java.nio.file.Files;
4
import java.nio.file.Path;
5
import java.nio.file.Paths;
6
7
public class SaveFileExample {
8
9
public static void main(String[] args) throws IOException {
10
11
String text = "Hello world";
12
Path path = Paths.get("C:\\test\\my-file.txt");
13
14
try (BufferedWriter writer = Files.newBufferedWriter(path)) {
15
writer.write(text);
16
writer.flush(); // ensure long text will be saved
17
}
18
}
19
}
By default Files.newBufferedWriter uses StandardCharsets.UTF_8 (java.nio.charset.StandardCharsets.UTF_8) encoding.
More examples:
0 commentsShow commentsAdd comment