The package java.nio.file replaced the old stream-based file API with one that is easier to use and harder to misuse. The paths are objects, the reading and the writing are static calls on the class Files, and every method that holds an open file supports the try-with-resources statement, so the handle is always closed.
This is the first lesson in the Java Multithreading, Files and the JVM module, and the next lesson in this module is about "How Do You Create and Run Threads in Java?".
What is a Path?
A Path is an object that represents the location of a file. You almost always build one with Paths.get or Path.of, and you combine the parts with resolve instead of concatenating the strings.
Path file = Paths.get("data", "value.txt");That form works the same on every operating system, because the separator is chosen by the platform rather than by you. The object carries the useful operations. There is getParent, there is getFileName, there is toAbsolutePath, and there is resolve for the joining.
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class SafeFiles {
public static void main(String[] args) throws Exception {
Path target = Paths.get("data");
Files.createDirectories(target);
Path file = target.resolve("value.txt");
Files.writeString(file, "42");
System.out.println("absolute : " + file.toAbsolutePath());
System.out.println("parent : " + file.getParent().getFileName());
System.out.println("extension : " + file.getFileName().toString().split("\\.")[1]);
System.out.println("exists : " + Files.exists(file));
System.out.println("is directory : " + Files.isDirectory(target));
System.out.println("missing file : " + Files.exists(Paths.get("no-such-file.txt")));
Files.deleteIfExists(file);
Files.deleteIfExists(target);
}
}The output is this.
absolute : C:\Users\iamfa\AppData\Local\Temp\opencode\jlw\data\value.txt
parent : data
extension : txt
exists : true
is directory : true
missing file : falseThe call resolve in the middle is the pattern to copy. You keep a directory as a Path and you join the file names to it, so you never build a path by pasting the strings together with a separator. The last two lines show the two questions that you will ask the most often. Does this exist, and is it a directory.
How do you read a whole file?
For a file that fits comfortably in memory, the method Files.readString gives you the whole content as one string, and the method Files.readAllLines gives you a list of the lines. Both of them are one-liners, and both of them specify a character set, so the result does not depend on the default encoding of the machine.
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
public class FileBasics {
public static void main(String[] args) throws Exception {
Path file = Paths.get("notes.txt");
Files.writeString(file, "first line\nsecond line\n");
System.out.println("exists : " + Files.exists(file));
System.out.println("size : " + Files.size(file));
String content = Files.readString(file);
System.out.println("read : " + content.strip());
List<String> lines = Files.readAllLines(file);
System.out.println("lines : " + lines.size());
Files.deleteIfExists(file);
System.out.println("exists after delete : " + Files.exists(file));
}
}The output is this.
exists : true
size : 23
read : first line
second line
lines : 2
exists after delete : falseNotice that the call Files.writeString created the file, and the call Files.deleteIfExists removed it without checking whether it was there. That method is the safe one to use in the cleanup code, because the "if exists" part is built in.
What about the large files?
Reading a huge file with readString loads all of it into the memory at once. For anything sizeable, you use a buffered reader and you process it line by line. The method Files.newBufferedReader gives you a BufferedReader, and the try-with-resources block closes it for you, even if an exception is thrown inside the loop.
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;
public class BufferedReading {
public static void main(String[] args) throws IOException {
Path file = Paths.get("rows.csv");
Files.writeString(file, "id,name\n1,ana\n2,bo\n", StandardCharsets.UTF_8);
try (BufferedReader reader = Files.newBufferedReader(file, StandardCharsets.UTF_8)) {
String line;
while ((line = reader.readLine()) != null) {
String[] parts = line.split(",");
System.out.println(parts.length + " columns, first is " + parts[0]);
}
}
try (Stream<String> lines = Files.lines(file, StandardCharsets.UTF_8)) {
long count = lines.filter(l -> l.contains(",")).count();
System.out.println("data rows : " + count);
}
Files.deleteIfExists(file);
}
}The output is this.
2 columns, first is id
2 columns, first is 1
2 columns, first is 2
data rows : 3The second part of that program uses the method Files.lines, which returns a stream of the lines. The stream must be closed too, which is why it sits inside a try-with-resources block. The streams are the more compact option, and they read the file lazily. Only the lines that the pipeline actually consumes are pulled from the disk.
How do you write to a file?
The method Files.writeString creates the file or overwrites it by default. To add to the end instead, you pass StandardOpenOption.APPEND. There is also the method Files.write, which takes a collection of the lines and writes them one per line.
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.List;
public class WritingOptions {
public static void main(String[] args) throws Exception {
Path file = Paths.get("log.txt");
Files.writeString(file, "first\n");
Files.writeString(file, "second\n", StandardOpenOption.APPEND);
Files.writeString(file, "third\n", StandardOpenOption.APPEND);
System.out.println("content :");
for (String line : Files.readAllLines(file)) {
System.out.println(" " + line);
}
Path listFile = Paths.get("items.txt");
Files.write(listFile, List.of("alpha", "beta"));
System.out.println("list : " + Files.readAllLines(listFile));
Files.copy(listFile, Paths.get("items-copy.txt"));
System.out.println("copy exists : " + Files.exists(Paths.get("items-copy.txt")));
Files.deleteIfExists(file);
Files.deleteIfExists(listFile);
Files.deleteIfExists(Paths.get("items-copy.txt"));
}
}The output is this.
content :
first
second
third
list : [alpha, beta]
copy exists : trueThe first block of the output shows the append behaviour. There are three writes and three lines, because the first write created the file and the next two appended to it. The second block shows the call Files.write with a list. The copy at the end is worth noting too. The method Files.copy makes a duplicate rather than a second name for the same bytes, and the method Files.move does the same for the renaming.
Why does the character encoding matter?
The text is bytes until it is decoded, and the decoding rules depend on a character set. If you write with one set and you read with another, or if you read with the default of the machine, then you can get the replacement characters where the accents or the non-Latin scripts should be.
The safe pattern is to pass StandardCharsets.UTF_8 explicitly at every read and every write, rather than to rely on Charset.defaultCharset() and hope that the machine agrees.
What are the safe habits with the files?
- Always close the file handles. Use try-with-resources and let the language do it.
- Always pass an explicit character set for the text.
- Use
deleteIfExistsrather than delete in the cleanup code. - Check Files.exists before you read a file that you did not create.
- Stream a large file line by line instead of reading it whole.
- Build the paths with resolve, and never with the string concatenation.
One more habit is worth forming. When you write a file that another program reads, you write to a temporary file and then you move it into the place. The move is usually atomic on the same filesystem, so a reader never sees a half-written file.
What else can you do with a file besides reading it?
The class Files reaches well past the contents of a file. It can tell you the size and the modification time, it can walk a directory tree, and it can create a temporary file for you when you only need somewhere to put the bytes.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant;
import java.util.stream.Stream;
public class FileMetadata {
public static void main(String[] args) throws IOException {
Path folder = Paths.get("notes");
Files.createDirectories(folder);
Path file = folder.resolve("day-one.txt");
Files.writeString(file, "first note");
System.out.println("size : " + Files.size(file));
System.out.println("has a modification time : " + (Files.getLastModifiedTime(file).toMillis() > 0));
System.out.println("is regular file : " + Files.isRegularFile(file));
try (Stream<Path> entries = Files.list(folder)) {
entries.forEach(entry -> System.out.println("entry : " + entry.getFileName()));
}
Path temp = Files.createTempFile("scratch", ".txt");
System.out.println("temp file created : " + Files.exists(temp));
Files.deleteIfExists(temp);
Files.deleteIfExists(file);
Files.deleteIfExists(folder);
}
}The output is this.
size : 10
has a modification time : true
is regular file : true
entry : day-one.txt
temp file created : trueThe method Files.list gives you the immediate children of a directory, and the method Files.walk gives you the whole tree. Both of them are streams that must be closed. The stream form is the right one, because it lets you filter and collect without holding every entry in the memory at once.
The call createTempFile deserves a mention because it removes a whole category of the bug. When two processes pick the names in the same folder by hand, they can collide. A temporary file is created atomically with a unique name, so the operating system guarantees that nobody else takes it.
The habits worth keeping
To summarise the API in one line each. The calls Paths.get and Path.of build a path, the call resolve joins the parts, the calls Files.readString and Files.readAllLines read, the calls Files.writeString and Files.write write, the calls Files.newBufferedReader and Files.lines stream, and the calls Files.copy, Files.move and Files.deleteIfExists manage the files on the disk.
Try it yourself: write a program that creates a folder, writes three small text files into it with the different content, reads them back with Files.readString, prints each file name with its character count, and then deletes the folder and everything in it. Add a step that copies one file before the deleting, and print the copy's content to prove that the copy survived.