Writing Files
Writing files is a common task in Java. This tutorial will teach you how to write data to files using different methods.
Using BufferedWriter
The BufferedWriter
class is used to write text to an output stream:
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter("example.txt"))) {
writer.write("Hello, World!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Using PrintWriter
The PrintWriter
class can also be used to write data to a file:
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class Main {
public static void main(String[] args) {
try (PrintWriter writer = new PrintWriter(new FileWriter("example.txt"))) {
writer.println("Hello, World!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Using Files Class
The Files
class provides methods for writing lines of text to a file:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List lines = Arrays.asList("Hello, World!", "Welcome to Java.");
try {
Files.write(Paths.get("example.txt"), lines);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Continue exploring our intermediate tutorials to learn more about Java programming.