EN
Java - save string to file
1
points
In this article we would like to show you how to save string to file in java.
Using BufferedWriter
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class SaveFileExample {
public static void main(String[] args) throws IOException {
String text = "Hello world";
Path path = Paths.get("C:\\test\\my-file.txt");
try (BufferedWriter writer = Files.newBufferedWriter(path)) {
writer.write(text);
writer.flush(); // ensure long text will be saved
}
}
}
By default Files.newBufferedWriter uses StandardCharsets.UTF_8 (java.nio.charset.StandardCharsets.UTF_8) encoding.
Using BufferedWriter with append to existing file
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
public class SaveFileAppendExample {
public static void main(String[] args) throws IOException {
String text = "--Hello world--";
Path path = Paths.get("C:\\test\\my-file.txt");
if (!Files.exists(path)) {
Files.createFile(path);
}
try (BufferedWriter writer = Files.newBufferedWriter(path,
StandardOpenOption.APPEND)) {
writer.write(text);
writer.append(", hello again");
writer.flush(); // ensure long text will be saved
}
}
}
If we execture above code 2 times, the file will contains below output:
--Hello world--, hello again--Hello world--, hello again
If we use BufferedWriter with APPEND option we need to ensure the file we want to save our data to exists. If the file doesn't exits we will get exception, that's why in above code we check if file exists and if not we create new one.
Using PrintWriter
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
public class SaveFileExample2 {
public static void main(String[] args) throws FileNotFoundException,
UnsupportedEncodingException {
String text = "Hello world";
String path = "C:\\test\\my-file.txt";
String charset = StandardCharsets.UTF_8.toString();
try (PrintWriter writer = new PrintWriter(path, charset)) {
writer.println(text);
writer.flush(); // ensure long text will be saved
}
}
}