Java File Handling
Java can create, read, write and delete files. The modern way is the java.nio.file package (Files and Path), which is simple and short.
Write and read a text file
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
public class Main {
public static void main(String[] args) throws IOException {
Path file = Path.of("notes.txt");
Files.writeString(file, "Java is fun.\nFiles are easy.\n");
System.out.println(Files.exists(file));
System.out.println(Files.size(file) + " bytes");
String text = Files.readString(file);
System.out.println(text);
List<String> lines = Files.readAllLines(file);
System.out.println(lines.size() + " lines, first: " + lines.get(0));
}
}
Output
true
29 bytes
Java is fun.
Files are easy.
2 lines, first: Java is fun.
Append and write many lines
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.List;
public class Append {
public static void main(String[] args) throws IOException {
Path file = Path.of("log.txt");
Files.write(file, List.of("line 1", "line 2")); // overwrite
Files.writeString(file, "line 3\n", StandardOpenOption.APPEND); // add at the end
System.out.println(Files.readString(file));
}
}
Output
line 1
line 2
line 3
Read a big file line by line
For big files do not load everything in the memory. Read with a stream or a BufferedReader. Both need try with resources, so the file is closed.
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
public class Big {
public static void main(String[] args) throws IOException {
Path file = Path.of("data.txt");
Files.write(file, List.of("apple", "banana", "cherry", "apricot"));
try (BufferedReader reader = Files.newBufferedReader(file)) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line.toUpperCase());
}
}
try (var lines = Files.lines(file)) {
System.out.println(lines.filter(l -> l.startsWith("a")).count() + " lines start with a");
}
}
}
Output
APPLE
BANANA
CHERRY
APRICOT
2 lines start with a
Copy, move and delete
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
public class Ops {
public static void main(String[] args) throws IOException {
Path a = Path.of("a.txt");
Files.writeString(a, "hello");
Path b = Path.of("b.txt");
Files.copy(a, b, StandardCopyOption.REPLACE_EXISTING);
Files.move(b, Path.of("c.txt"), StandardCopyOption.REPLACE_EXISTING);
System.out.println(Files.exists(a) + " " + Files.exists(b) + " " + Files.exists(Path.of("c.txt")));
Files.delete(a);
System.out.println(Files.deleteIfExists(a)); // false: already gone
}
}
Output
true false true
false
Folders
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Stream;
public class Dirs {
public static void main(String[] args) throws IOException {
Path dir = Files.createDirectories(Path.of("project/docs"));
Files.writeString(dir.resolve("readme.txt"), "Hello");
Files.writeString(Path.of("project", "main.txt"), "Main");
try (Stream<Path> paths = Files.walk(Path.of("project"))) {
paths.sorted().forEach(System.out::println);
}
System.out.println(Files.isDirectory(dir));
}
}
Output
project
project/docs
project/docs/readme.txt
project/main.txt
true
File not found
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
public class Missing {
public static void main(String[] args) {
try {
Files.readString(Path.of("does-not-exist.txt"));
} catch (NoSuchFileException e) {
System.out.println("File not found: " + e.getMessage());
} catch (IOException e) {
System.out.println("Other problem: " + e);
}
}
}
Output
File not found: does-not-exist.txt
Old classes you will still see
In older code you will find File, FileReader, FileWriter and Scanner(new File(...)). They still work, but Files and Path are simpler and safer for new code.
Note:
File methods throw a checked IOException, so handle it or add throws IOException. Next: Java Threads.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |