Reading and Writing Text Files in Java
Files.readString reads tasks.txt in one call and readAllLines splits it into three tasks. writeString makes a shopping list that Files.lines filters to 2 items starting with B, a BufferedWriter writes an invoice, a Scanner totals 257, and Café is 4 characters but 5 bytes.
What you will learn
- Read a small file with Files.readString and Files.readAllLines
- Write a file with Files.writeString and read a big one line by line with Files.lines
- Write and read with BufferedWriter and BufferedReader inside try-with-resources
- Read words and numbers with Scanner, and keep text safe with UTF-8
Before you start
- Java files and directories with NIO.2
- Java try-with-resources and clean error handling
In modern Java, reading a whole file can be one line. This lesson covers the one-call methods for small files, line-by-line reading for big ones, buffered readers and writers, Scanner, and charsets. All these methods throw the checked IOException, so each main declares throws IOException.
Read a whole file
package org.studyeasy.s07l02;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
public class Ex01_ReadExisting {
public static void main(String[] args) throws IOException {
// tasks.txt is already in the project folder
Path tasks = Path.of("tasks.txt");
// the whole file as one String, line breaks and all
String text = Files.readString(tasks);
System.out.print(text);
// the same file, one List element per line
List<String> lines = Files.readAllLines(tasks);
System.out.println(lines.size() + " tasks: " + lines);
System.out.println("First: " + lines.get(0));
}
}
Buy milk
Call Emma
Pay rent
3 tasks: [Buy milk, Call Emma, Pay rent]
First: Buy milk
A text file is just lines, each ending with a line break (\n). readString takes the whole thing as one String with the line breaks inside. readAllLines cuts at every break and gives a List, one task per element. A typo in the path, such as "task.txt", stops it with NoSuchFileException.
Create a file, then read it back
Path shopping = Path.of("shopping.txt");
// \n ends a line: this text is 4 lines in the file
Files.writeString(shopping, "Milk\nBread\nButter\nEggs\n");
List<String> items = Files.readAllLines(shopping);
System.out.println(items.size() + " items: " + items);
// a stream reads one line at a time: close it with try
try (Stream<String> lines = Files.lines(shopping)) {
long b = lines.filter(line -> line.startsWith("B")).count();
System.out.println("Start with B: " + b);
}
4 items: [Milk, Bread, Butter, Eggs]
Start with B: 2
writeString creates the file, or replaces what was there. Files.lines is a stream that hands over one line at a time instead of loading everything, which matters for big files; it holds the file open, so it goes in try-with-resources. Bread and Butter start with B. startsWith is case sensitive, so "b" would count 0.
Write and read line by line
Path invoice = Path.of("invoice.txt");
String[] items = {"Keyboard,45", "Monitor,240", "Webcam,60"};
try (BufferedWriter out = Files.newBufferedWriter(invoice)) {
for (String item : items) {
out.write(item);
out.newLine(); // this OS's line break
}
} // close(): the buffer goes to disk
try (BufferedReader in = Files.newBufferedReader(invoice)) {
String line;
while ((line = in.readLine()) != null) { // null: the end
System.out.println(line);
}
}
Keyboard,45
Monitor,240
Webcam,60
For many lines, a BufferedWriter collects text in a buffer and writes it in big blocks; newLine() adds this system's line break. Closing it (here, the end of the try-with-resources block) pushes the buffer to disk. Skip the try and it's never closed, so the file can stay empty. readLine() returns one line at a time and null at the end. Path and Files live in java.nio.file; the buffered classes in java.io.
Read words and numbers with Scanner
Path scores = Path.of("scores.txt");
Files.writeString(scores, "Emma 87\nJack 92\nTom 78\n");
int total = 0;
try (Scanner sc = new Scanner(scores)) { // splits on spaces
while (sc.hasNext()) {
sc.next(); // "Emma": a word
total += sc.nextInt(); // 87: an int
}
}
System.out.println("Scanner total: " + total);
try (BufferedReader in = Files.newBufferedReader(scores)) {
System.out.println("readLine: " + in.readLine());
}
Scanner total: 257
readLine: Emma 87
The Scanner you used for keyboard input reads files too, splitting on spaces: a word, a number, a word, a number. 87 + 92 + 78 is 257. Delete sc.next() and nextInt() meets the word Emma: InputMismatchException. A BufferedReader gives the whole line instead.
Characters are not bytes
Path menu = Path.of("menu.txt");
String word = "Café";
Files.writeString(menu, word, UTF_8);
System.out.println("Characters: " + word.length());
System.out.println("Bytes: " + Files.size(menu));
// read with the charset it was written in...
System.out.println(Files.readString(menu, UTF_8));
// ...or é turns into two wrong characters
System.out.println(Files.readString(menu, ISO_8859_1));
Characters: 4
Bytes: 5
Café
Café
A charset decides how text becomes bytes and back. In UTF-8, C, a and f take one byte each, but é takes two (C3 A9), so four characters make five bytes. Read with UTF-8, the two bytes come back as one é. Read with ISO-8859-1, each byte becomes its own character, and you get "é". Use UTF-8 both ways. (The one-call Files methods default to UTF-8.)
Pick the tool for the job
| Job | Use |
|---|---|
| Small file, all at once | readString, readAllLines, writeString |
| Big file, line by line | Files.lines or BufferedReader in a try |
| Many lines to write | BufferedWriter with newLine |
| Words and numbers | Scanner |
| Text with accents | UTF-8 both ways |
Next: files with structure, in JSON and CSV.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
Java Files and Directories with NIO.2: Path and Files
Path.of("invoices", "2026", "inv-101.pdf") is only an address: getFileName, getParent and resolve work, but nothing is on disk. Files.createDirectories and createFile make an order file and delete removes it, Files.walk finds 4 .java files, and os.name tells Windows from Linux.
Java Structured Data: Reading and Writing JSON and CSV
Two Student records, Emma Clark with 91 in Java and Liam Brown with 78 in SQL, saved two ways. Jackson's ObjectMapper writes them to students.json and reads them back in one call each; plain Java writes students.csv with a header and reads it back by splitting at the commas.
