Reading & Writing Files
Java provides comprehensive tools to read from and write to files. The java.io package offers classic streams, while java.nio provides modern, efficient file operations. Learning file I/O is essential for any practical application.
40 min•By Priygop Team•Last updated: Feb 2026
File I/O Basics
File I/O (Input/Output) is how programs interact with files on disk. Java provides two main approaches: the classic java.io package (FileReader, BufferedReader, FileWriter) and the modern java.nio.file package (Files, Path). The newer API is generally recommended for its simplicity and performance.
File Reading & Writing
Example
import java.io.*;
import java.nio.file.*;
import java.util.*;
public class FileIODemo {
public static void main(String[] args) {
String filename = "demo.txt";
// === Writing to a file ===
try (FileWriter writer = new FileWriter(filename)) {
writer.write("Hello, Java File I/O!\n");
writer.write("Line 2: Learning file operations\n");
writer.write("Line 3: This is awesome!\n");
System.out.println("File written successfully!");
} catch (IOException e) {
System.out.println("Write error: " + e.getMessage());
}
// === Reading from a file ===
try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
String line;
int lineNum = 1;
System.out.println("\n=== Reading File ===");
while ((line = reader.readLine()) != null) {
System.out.println(lineNum + ": " + line);
lineNum++;
}
} catch (IOException e) {
System.out.println("Read error: " + e.getMessage());
}
// === Modern NIO approach ===
try {
// Write all lines at once
List<String> lines = Arrays.asList(
"Name,Age,City",
"Alice,25,New York",
"Bob,30,London",
"Charlie,28,Tokyo"
);
Files.write(Path.of("data.csv"), lines);
// Read all lines at once
System.out.println("\n=== CSV Data ===");
List<String> readLines = Files.readAllLines(Path.of("data.csv"));
for (String csvLine : readLines) {
System.out.println(csvLine);
}
} catch (IOException e) {
System.out.println("NIO error: " + e.getMessage());
}
}
}Try It Yourself: Log File Manager
Try It Yourself: Log File ManagerJava
Java Editor
✓ ValidTab = 2 spaces
Java|52 lines|1957 chars|✓ Valid syntax
UTF-8