Reading and writing files is a function that almost every program needs. Focusing on Files and Path of Java's new IO API, java.nio.file, you will learn the try-with-resources pattern to prevent resource leaks.
Learning Objectives
- Know the role of
PathandFiles - Read and write text files with
Files.readAllLines/Files.writeString - Know how to use
BufferedReaderandtry-with-resources - Understand that
IOExceptionis a checked exception.
Key concepts
1) Path and Files
import java.nio.file.Path;
import java.nio.file.Files;
Path p = Path.of("data.txt");
Files.writeString(p, "Hello\nWorld\n");
String text = Files.readString(p);
Path is an immutable object representing a path, and Files is a collection of static utilities.
2) Line-by-line input/output
List<String> lines = Files.readAllLines(Path.of("data.txt"));
Files.write(Path.of("out.txt"), lines); //Write the lines as they are
3) try-with-resources
try (BufferedReader br = Files.newBufferedReader(p)) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
//br.close() is called automatically
Any resource that implements AutoCloseable can be used.
4) checked exception IOException
File IO methods are mostly checked exceptions that throw IOException. A throws IOException declaration or try/catch is required.
See as example
Example 1 — WriteFile.java: Write file
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class WriteFile {
public static void main(String[] args) throws IOException {
Path p = Path.of("greeting.txt");
Files.writeString(p, "Hello\nHello\n");
System.out.println(p.toAbsolutePath() + "Write complete");
}
}
Execution result
Completed writing /.../greeting.txt
Memo: If the file does not exist, it will be automatically created, and if it exists, it will be overwritten.
Example 2 — ReadFile.java: Reading file
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
public class ReadFile {
public static void main(String[] args) throws IOException {
Path p = Path.of("greeting.txt");
Files.writeString(p, "Hello\nHello\n");
List<String> lines = Files.readAllLines(p);
for (int i = 0; i < lines.size(); i++) {
System.out.println((i + 1) + ": " + lines.get(i));
}
}
}
Execution result
1: Hello
2: Hello
Note: Reading line by line makes things like numbering easier.
Example 3 — BufferedReadDemo.java : try-with-resources
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class BufferedReadDemo {
public static void main(String[] args) throws IOException {
Path p = Path.of("greeting.txt");
Files.writeString(p, "Hello\nHello\n");
try (BufferedReader br = Files.newBufferedReader(p)) {
String line;
int n = 0;
while ((line = br.readLine()) != null) {
n++;
System.out.printf("L%d: %s%n", n, line);
}
}
}
}
Execution result
L1: Hello
L2: Hello
Note: br.close() is automatically called at the end of the try block.
Example 4 — AppendAndDelete.java: Add + Delete
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
public class AppendAndDelete {
public static void main(String[] args) throws IOException {
Path p = Path.of("notes.txt");
Files.writeString(p, "first line\n");
Files.writeString(p, "Second line\n", StandardOpenOption.APPEND);
System.out.println(Files.readString(p));
Files.deleteIfExists(p);
System.out.println("Deletion complete");
}
}
Execution result
first line
second line
Deletion complete
Memo: StandardOpenOption.APPEND can be added after existing content.
Common Mistakes
- OS handle leak due to not closing file resources → Use try-with-resources
- Hard-code the path separator for each OS → Use
Path.of/Path.resolve - Korean text is broken because encoding is not specified →
Files.readString(path, StandardCharsets.UTF_8)is recommended - Propagate without having to use
IOExceptionevery time → In the introductory stage,throws IOExceptionin main is sufficient. - Does not consider situations where multiple threads are writing the same file at the same time (outside the scope of this tutorial)
Cleanup
Path+Filesis the center of modern Java IOtry-with-resourcesis the standard pattern for resource release- Large files are processed line by line + buffering is safe
- UTF-8 encoding is recommended.
Try it yourself
cd 04_Exception_Input/Output/16_File_IO/src
javac WriteFile.java
java WriteFile