Video in progress
How can you read a small text file with a single line of code?
Files.readString(path) (Java 11+) gives you the whole file as one String, and Files.readAllLines(path) gives a list of lines. Both use UTF-8 by default and close the file themselves.
📖 Answer
Path cfg = Path.of("config/app.txt");
String all = Files.readString(cfg); // the whole text
List<String> lines = Files.readAllLines(cfg); // lines
byte[] raw = Files.readAllBytes(cfg); // raw bytes
There are matching methods for writing too: Files.writeString(path, text) and Files.write(path, lines).
One catch: these methods load the whole file into memory. They are great for configuration, a small template, a test fixture. Use them on a 2 GB log file and you get OutOfMemoryError. For big files, read line by line with Files.lines or BufferedReader.
If the file is in a different encoding, pass the charset explicitly: Files.readString(cfg, Charset.forName("windows-1251")).
Sign up to mark studied questions and save your progress.