Intermediate 8 min
Paths and text files
A Path describes a file or folder location, and Files provides operations that use that location.
How it works
A Path describes where to look. Creating one does not read or create the file. Files.readString then tries to open and decode it. Keeping these steps separate helps you distinguish a wrong path from content that could not be processed.
Walk through an example
Use Path.of("data", "notes.txt") to create a relative path. Files.readString(path) reads the text and reports failures with an exception.
What to watch for
A relative path is resolved from the process’s working directory. For large inputs, prefer processing chunks or lines to loading the entire file at once.
Check your understanding
Which file is selected?
See the example and explanation
- Worked example
- Given
The current directory is /work and the relative path is data/notes.txt. - Answer
/work/data/notes.txt
The current directory supplies the starting point for the relative path.