Java Text Input and Output: PrintWriter, BufferedReader and Saving Objects as Text
Read and write text in Java: Files.readString, readAllLines and lines, Scanner tokens and the nextLine trap, BufferedReader, Java 25's Reader.readAllLines, PrintWriter with print, println, printf, autoflush and checkError, and saving records in a delimited text format.
kvi5hnuCode Sprout team member10 min readOn this page
When you save data, you choose between a binary format and a text format. The integer 1234 in binary is the four bytes 00 00 04 D2 (in hexadecimal). As text, it's the characters "1234". Binary is compact and fast to process, but people can't read it. Text is readable, easy to debug and easy to exchange between programs. This article covers text. Binary formats follow in article 22.
From characters to bytes and back
Java strings are made of UTF-16 code units, but files contain bytes, so text I/O always involves a character encoding that maps characters to bytes. In UTF-16, "José" is 00 4A 00 6F 00 73 00 E9. In UTF-8, the dominant encoding today, the same string is 4A 6F 73 C3 A9: one byte for each ASCII letter and two for é. The next article explains encodings in depth.
Two bridge classes do the conversion. OutputStreamWriter turns characters into bytes and writes them to an output stream. InputStreamReader reads bytes from an input stream and decodes them into characters. Since Java 18, both default to UTF-8 (JEP 400). Before that, the default depended on the operating system, which was a constant source of bugs. Passing the charset explicitly costs nothing and documents your intent:
var in = new InputStreamReader(new FileInputStream("data.txt"), StandardCharsets.UTF_8);
Reader and Writer themselves only read and write characters. For lines, tokens and numbers, you use the classes and methods below.
Reading text
For whole files, the Files class (article 26) has the simplest options:
String content = Files.readString(path); // the whole file as one string
List<String> lines = Files.readAllLines(path); // a list of lines
try (Stream<String> lines = Files.lines(path)) { // lazily, for large files
...
}
Files.lines reads lines on demand, so it works for files of any size. Close the stream, with try-with-resources as shown, because it holds the file open. If an IOException happens while lines are being fetched, it's wrapped in an UncheckedIOException, since stream operations can't throw checked exceptions.
readAllLines and lines strip the line terminators, recognizing \n, \r\n and \r alike. readString returns the content unchanged, terminators included.
BufferedReader
BufferedReader reads a line at a time with readLine(), which returns null at the end. Its lines() method returns a stream of the remaining lines. Get one from Files.newBufferedReader(path) or by wrapping any reader. The classic loop is still common in existing code:
try (BufferedReader reader = Files.newBufferedReader(path)) {
String line;
while ((line = reader.readLine()) != null) {
process(line);
}
}
In new code, Files.lines or reader.lines() are usually neater. A BufferedReader is still the tool of choice for reading lines from a non-file source, such as a process or a socket.
Java 24 and 25 additions to Reader
Reader.of(CharSequence) (Java 24) gives a reader over a string, a lighter replacement for new StringReader(s). Java 25 added readAllLines() and readAllAsString() to every Reader, so reading everything from any reader, not just a file, is now one call:
List<String> lines = reader.readAllLines();
String text = reader.readAllAsString();
Scanner
Scanner parses text into lines, tokens and numbers. It can read from a Path, an InputStream, a Reader or a String:
try (var in = new Scanner(path, StandardCharsets.UTF_8)) {
while (in.hasNextLine()) {
String line = in.nextLine();
...
}
}
Tokens are separated by a delimiter, whitespace by default. You can set any regular expression. With useDelimiter("\\PL+"), all non-letters separate tokens, so each token is a word. next() returns the next token, and tokens() returns them all as a stream.
nextInt() and nextDouble() parse numbers. Call hasNextInt() or hasNextDouble() first to check. Numbers are parsed according to the scanner's locale: in a German locale, nextDouble expects 29,95, not 29.95. For machine-written data, call useLocale(Locale.ROOT).
Writing text
For text output, use PrintWriter. It has print, println and printf methods for strings, numbers, characters, booleans and objects (via toString):
var out = new PrintWriter("employee.txt", StandardCharsets.UTF_8);
out.print("Omar Haddad");
out.print(' ');
out.println(68000.0); // writes: Omar Haddad 68000.0
A few facts worth knowing:
PrintWriterhas constructors for a file name orFile, but oddly not for aPath. Usenew PrintWriter(Files.newBufferedWriter(path)), or theFileconstructor withpath.toFile().printlnwrites the platform's line separator ("\r\n"on Windows,"\n"elsewhere), which isSystem.lineSeparator(). Useprintwith"\n"if you need a fixed line ending.- A print writer is buffered. With autoflush enabled, through the
PrintWriter(Writer, boolean)orPrintWriter(OutputStream, boolean)constructors,println,printfandformatflush the buffer. Autoflush is off by default. - The print methods never throw exceptions. If the underlying output fails, say because the disk is full, the error is recorded silently. Call
checkError()to find out. Once an error has occurred, it keeps returningtrue. Check it at least once at the end when output really matters.
PrintStream and System.out
System.out and System.err are PrintStreams, a byte stream class from Java 1.0. Back then, PrintStream simply chopped every character down to its low byte. Readers and writers were introduced in Java 1.1 to do it properly. For compatibility, System.in, System.out and System.err stayed byte streams, but PrintStream now encodes characters properly, using stdout.encoding for the console. A PrintStream behaves like a PrintWriter for print and println, and it can also write raw bytes with write. In Java 25, IO.println and IO.readln (Volume I) are the simplest console methods.
Saving objects in text format
Here's a simple way to save records as text: one record per line, with the fields separated by a delimiter character. The vertical bar | is a common choice, as is a colon, a tab or a comma:
Priya Nair|68000.0|2016-04-11
Omar Haddad|52000.0|2019-09-02
Lena Fischer|46000.0|2021-06-21
Writing is one println per record:
out.println(e.name() + "|" + e.salary() + "|" + e.startDate());
Reading splits each line into its fields:
String[] tokens = in.nextLine().split("\\|");
var e = new Employee(tokens[0], Double.parseDouble(tokens[1]), LocalDate.parse(tokens[2]));
The argument of split is a regular expression (article 36). In regex syntax, | means "or", so it must be escaped as \|, and since the backslash is itself escaped in Java string literals, you write "\\|".
The demo program first writes the number of records, then the records. Reading the count with nextInt() leaves the line ending behind, so the code calls nextLine() once to skip it, the trap from above.
This simple format falls apart as soon as a field contains the delimiter or a line break. Real formats such as CSV handle that with quoting rules, and JSON handles it with escapes. For anything beyond toy data, use a proper format, typically through a library. Article 32 shows Java's own serialization, and Part 3 covers XML.
A complete example
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.*;
public class Solution {
record Employee(String name, double salary, LocalDate startDate) {}
static void writeData(List<Employee> employees, PrintWriter out) {
out.println(employees.size());
for (Employee e : employees)
out.println(e.name() + "|" + e.salary() + "|" + e.startDate());
}
static List<Employee> readData(Scanner in) {
int n = in.nextInt();
in.nextLine(); // consume the rest of the first line
var employees = new ArrayList<Employee>();
for (int i = 0; i < n; i++) {
String[] tokens = in.nextLine().split("\\|");
employees.add(new Employee(tokens[0], Double.parseDouble(tokens[1]), LocalDate.parse(tokens[2])));
}
return employees;
}
public static void main(String[] args) throws IOException {
Path file = Files.createTempFile("employee", ".txt");
List<Employee> staff = List.of(
new Employee("Priya Nair", 68000, LocalDate.of(2016, 4, 11)),
new Employee("Omar Haddad", 52000, LocalDate.of(2019, 9, 2)),
new Employee("Lena Fischer", 46000, LocalDate.of(2021, 6, 21)));
// write text with a PrintWriter (UTF-8 is the default since Java 18)
try (var out = new PrintWriter(file.toFile(), StandardCharsets.UTF_8)) {
writeData(staff, out);
}
System.out.println("file:\n" + Files.readString(file).strip());
// read it back with a Scanner
try (var in = new Scanner(file, StandardCharsets.UTF_8)) {
List<Employee> copy = readData(in);
System.out.println("read back equal: " + copy.equals(staff));
System.out.println("first: " + copy.getFirst());
}
// whole file, all lines, lazy lines
List<String> lines = Files.readAllLines(file);
System.out.println("line count: " + lines.size());
try (Stream<String> stream = Files.lines(file)) {
System.out.println("lines containing 'Haddad': " + stream.filter(l -> l.contains("Haddad")).toList());
}
// BufferedReader: line by line, or as a stream
try (BufferedReader reader = Files.newBufferedReader(file)) {
String first = reader.readLine();
System.out.println("first line: " + first + ", remaining: " + reader.lines().count());
}
Files.delete(file);
// Scanner tokens with a custom delimiter
var words = new Scanner("Mary had a little lamb, its fleece was white as snow.");
words.useDelimiter("\\PL+");
System.out.println("tokens: " + words.tokens().toList());
// the nextDouble/nextLine trap
var in = new Scanner("29.95\nBlackwell Toaster\n").useLocale(Locale.ROOT);
double price = in.nextDouble();
String wrong = in.nextLine();
String description = in.nextLine();
System.out.println("price " + price + ", first nextLine: \"" + wrong + "\", second: \"" + description + "\"");
// checking for numbers before reading them
var mixed = new Scanner("12 apples 7 pears x");
int total = 0;
while (mixed.hasNext()) {
if (mixed.hasNextInt()) total += mixed.nextInt();
else mixed.next();
}
System.out.println("sum of the numbers: " + total);
// Java 24 Reader.of and Java 25 readAllLines / readAllAsString
Reader reader = Reader.of("alpha\nbeta\r\ngamma");
System.out.println("Reader.readAllLines: " + reader.readAllLines());
System.out.println("readAllAsString length: " + Reader.of("hello").readAllAsString().length());
// PrintWriter into a StringWriter, with printf
var sw = new StringWriter();
try (var out = new PrintWriter(sw)) {
out.print("Omar Haddad");
out.print(' ');
out.println(68000.0);
out.printf(Locale.ROOT, "%-8s|%8.2f%n", "Lena", 46000.0);
}
System.out.print(sw.toString().replace(System.lineSeparator(), "\n"));
// print methods don't throw; checkError reports problems
var broken = new PrintWriter(new Writer() {
@Override public void write(char[] cbuf, int off, int len) throws IOException { throw new IOException("disk full"); }
@Override public void flush() { }
@Override public void close() { }
});
broken.println("lost");
System.out.println("checkError after a failed write: " + broken.checkError());
}
}
file:
3
Priya Nair|68000.0|2016-04-11
Omar Haddad|52000.0|2019-09-02
Lena Fischer|46000.0|2021-06-21
read back equal: true
first: Employee[name=Priya Nair, salary=68000.0, startDate=2016-04-11]
line count: 4
lines containing 'Haddad': [Omar Haddad|52000.0|2019-09-02]
first line: 3, remaining: 3
tokens: [Mary, had, a, little, lamb, its, fleece, was, white, as, snow]
price 29.95, first nextLine: "", second: "Blackwell Toaster"
sum of the numbers: 19
Reader.readAllLines: [alpha, beta, gamma]
readAllAsString length: 5
Omar Haddad 68000.0
Lena |46000.00
checkError after a failed write: true
The demo uses Locale.ROOT for the scanner and for printf, so its output doesn't depend on the locale of the computer it runs on.
Common questions
How do I read user input from the console?
In Java 25, IO.readln("Prompt: ") prints a prompt and reads a line. Before that, new Scanner(System.in) with nextLine() or nextInt() is the usual choice, or new BufferedReader(new InputStreamReader(System.in)).readLine(). Create one scanner for the whole program, and don't close it, because closing it closes System.in. Article 75 covers Console for passwords.
Scanner or BufferedReader for large input?
BufferedReader is much faster, because Scanner runs regular expressions for every token. For reading millions of numbers, as in programming contests, read lines with a BufferedReader and split them yourself, or use StreamTokenizer. For ordinary interactive input, Scanner is convenient and fast enough.
What is the simplest way to write a text file?
Files.writeString(path, text) or Files.write(path, lines) for a list of lines, both UTF-8 by default. Pass StandardOpenOption.APPEND to append. Use a PrintWriter or BufferedWriter when you produce output piece by piece.
How do I parse a CSV file?
Splitting on , works only for simple files without quoted fields. Real CSV allows commas and line breaks inside quotes, so use a library such as Apache Commons CSV or OpenCSV in production code.
Why does my file contain strange characters when I read it?
The file was written in a different encoding from the one you read it with, for example Windows-1252 read as UTF-8. Pass the right Charset when reading. The next article explains encodings.
Can Files.readAllLines handle a 10 GB file?
It would try to hold all the lines in memory and fail with an OutOfMemoryError. Use Files.lines or a BufferedReader, which read line by line.
API reference
java.io.PrintWriter
| Method | Description |
|---|---|
PrintWriter(Writer out), PrintWriter(Writer out, boolean autoFlush), PrintWriter(OutputStream out), PrintWriter(OutputStream out, boolean autoFlush) | write to a writer or stream; with autoFlush, println, printf and format flush |
PrintWriter(String fileName, Charset charset), PrintWriter(File file, Charset charset) (Java 10) | write to a file with the given encoding |
void print(Object obj) and overloads for String, char[], char, int, long, float, double, boolean | print a value as text |
void println(...) | print, then a line separator |
PrintWriter printf(String format, Object... args), printf(Locale l, String format, Object... args) | print formatted values (Volume I, Part 3) |
boolean checkError() | flushes and reports whether an error has ever occurred |
java.util.Scanner
| Method | Description |
|---|---|
Scanner(Path source, Charset charset), Scanner(InputStream source), Scanner(String source) | scan a file, stream or string |
boolean hasNextLine(), String nextLine() | test for and read the next line (rest of the current line) |
boolean hasNext(), String next() | test for and read the next token |
boolean hasNextInt(), int nextInt(), boolean hasNextDouble(), double nextDouble() | test for and parse numbers |
Scanner useDelimiter(String pattern), Scanner useLocale(Locale locale) | set the token delimiter and the number locale |
Stream<String> tokens() (Java 9) | a stream of the remaining tokens |
java.io.BufferedReader and java.io.Reader
| Method | Description |
|---|---|
String readLine() | the next line, without terminator, or null at the end |
Stream<String> lines() | a lazy stream of the remaining lines |
static Reader of(CharSequence cs) (Java 24) | a reader over a character sequence |
List<String> readAllLines(), String readAllAsString() (Java 25) | read all remaining characters as lines or as a string |
java.nio.file.Files
| Method | Description |
|---|---|
String readString(Path path), List<String> readAllLines(Path path) | read a whole text file (UTF-8 unless a Charset is given) |
Stream<String> lines(Path path) | a lazy stream of lines; close it after use |
BufferedReader newBufferedReader(Path path), BufferedWriter newBufferedWriter(Path path, OpenOption... options) | buffered text access to a file |
Summary
- Text I/O converts characters to bytes with an encoding.
InputStreamReaderandOutputStreamWriterare the bridges, and UTF-8 is the default since Java 18. - Read whole files with
Files.readString,readAllLinesor the lazyFiles.lines. UseBufferedReaderfor line-by-line reading from other sources, and Java 25'sReader.readAllLinesandreadAllAsStringfor any reader. Scannerreads tokens and numbers, using the locale for number format. AfternextIntornextDouble, the rest of the line is still waiting, so callnextLineto skip it.PrintWriterwrites text withprint,printlnandprintf. It never throws, so checkcheckError(). It can't be constructed from aPathdirectly.- Delimited text is a quick way to save records, but use a real format such as CSV or JSON when fields may contain delimiters or newlines.
Practice Questions
Why is "\|" used in line.split("\|") rather than "|"?
split takes a regular expression, in which | means alternation ("or"). "|" alone would split between every character. \| matches a literal bar, and in a Java string literal the backslash must be doubled, giving "\\|".
Input is "3\nAlice\nBob\nCarol". After in.nextInt(), the first in.nextLine() returns "". Why, and how do you fix it?
nextInt consumes only the token 3, leaving the line break. nextLine then returns the rest of that line, which is empty. Call in.nextLine() once right after nextInt() to skip it, then read the names.
A program's output file is missing its last lines, and no exception was thrown. What are two likely causes when using PrintWriter?
The writer was never closed or flushed, so the buffered text was never written. Or a write failed, for example because the disk was full, and PrintWriter swallowed the error. Close it with try-with-resources and check checkError().
How do you count the lines of a 10 GB log file without loading it into memory?
try (Stream<String> lines = Files.lines(path)) { long count = lines.count(); }. The stream reads lines lazily, and try-with-resources closes the file.
Your program parses "29.95" with Scanner.nextDouble and works on your machine but fails for a colleague in France. Why?
Scanner parses numbers according to its locale, and the French locale uses a comma as the decimal separator, so 29.95 isn't a valid number there. For machine-generated data, call scanner.useLocale(Locale.ROOT), or parse with Double.parseDouble, which is locale-independent.
Previous: Java I/O Filters: Buffered, Data and Pushback Streams
Next: Java Character Encodings: UTF-8, Charsets and the Default Encoding
Related reading
- Java I/O Filters: Buffered, Data and Pushback Streams
- Java I/O Streams: Reading and Writing Bytes
- Java Parallel Streams: When They Help, Ordering and Thread Safety
- Java Primitive Streams: IntStream, LongStream and DoubleStream
- Implementing Java Stream Gatherers: Integrators, State, Short-Circuiting and Parallelism

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.