Java File Input and Output Basics: Reading and Writing Text Files
Read text files with Scanner and Path.of, write them with PrintWriter, and use the modern Files.readString, readAllLines and writeString. Covers UTF-8 and character encodings, relative paths and the working directory, throws IOException, try-with-resources, and shell redirection.
kvi5hnuCode Sprout team member10 min readOn this page
Console programs forget everything when they end. To keep data (scores, settings, logs, reports) you need files. Reading and writing text files in Java uses the same tools you already know: a Scanner to read, and print/println/printf to write.
This article covers the basics you need for exercises and small programs. Advanced topics (binary data, directory walking, zip files, memory-mapped files) belong to the full I/O API, but the techniques here handle most everyday tasks.
Reading a File with Scanner
To read a file, construct a Scanner from a Path:
import java.nio.file.Path;
import java.util.Scanner;
Scanner in = new Scanner(Path.of("myfile.txt"));
Path.of (Java 11; Paths.get in older code) turns a file name into a Path object, which represents a location in the file system. After that, all the Scanner methods from the previous article work: nextLine, next, nextInt, hasNext, and so on.
On Windows, remember that a backslash in a Java string must be escaped: "c:\\mydirectory\\myfile.txt". Forward slashes also work on Windows ("c:/mydirectory/myfile.txt") and are easier to read.
Writing a File with PrintWriter
To write text, construct a PrintWriter with a file name:
import java.io.PrintWriter;
PrintWriter out = new PrintWriter("myfile.txt");
out.println("Hello, file!");
out.printf("%d squared is %d%n", 7, 49);
out.close();
- If the file doesn't exist, it's created. If it exists, it's overwritten (emptied first).
print,printlnandprintfwork exactly like onSystem.out.- You must close the writer (or at least
flushit).PrintWritercollects output in a memory buffer and writes it to disk in larger blocks. If the program ends withoutclose(), the last part of the output can be lost, and you might find an empty file.
Exceptions: throws IOException
Files can be missing, unreadable or on a full disk. If the file for a Scanner doesn't exist, or a PrintWriter can't create its file, Java throws an exception.
These I/O exceptions are checked exceptions: the compiler insists that you acknowledge them. Until the exceptions part teaches you to handle them properly with try/catch, the simplest approach is to declare that main may throw them, by adding a throws clause:
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(Path.of("myfile.txt"));
...
}
Without it, you get a compile error like:
error: unreported exception IOException; must be caught or declared to be thrown
IOException is in java.io, so add import java.io.IOException;. If the file is missing at runtime, the program stops with a java.nio.file.NoSuchFileException (a kind of IOException) and a stack trace, which is acceptable behaviour for a small exercise.
Closing Files Automatically: try-with-resources
Calling close() by hand is easy to forget, and it's skipped entirely if an exception happens first. The try-with-resources statement closes files for you, whatever happens:
try (PrintWriter out = new PrintWriter("scores.txt")) {
out.println("Ada 92");
} // out.close() is called automatically here
Any object declared in the parentheses after try is closed when the block ends. It's the recommended way to work with files. The details (multiple resources, suppressed exceptions) come in the exceptions part. For now, use the pattern.
A Complete Example
This program writes a small file of names and scores, reads it back token by token to compute an average, and then shows the modern one-call methods of the Files class:
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Scanner;
public class Solution {
public static void main(String[] args) throws IOException {
try (PrintWriter out = new PrintWriter("scores.txt")) {
out.println("Ada 92");
out.println("Linus 85");
out.printf("%s %d%n", "Grace", 97);
}
int total = 0;
int count = 0;
try (Scanner in = new Scanner(Path.of("scores.txt"))) {
while (in.hasNext()) {
String name = in.next();
int score = in.nextInt();
System.out.println(name + " -> " + score);
total += score;
count++;
}
}
System.out.printf("Average: %.2f%n", (double) total / count);
String all = Files.readString(Path.of("scores.txt"));
System.out.print(all);
List<String> lines = Files.readAllLines(Path.of("scores.txt"));
System.out.println(lines.size() + " lines, first = " + lines.get(0));
Files.writeString(Path.of("note.txt"), "Héllo, wörld ✓\n");
System.out.println(Files.size(Path.of("note.txt")) + " bytes");
System.out.println(Files.readString(Path.of("note.txt")).length() + " chars");
System.out.println(Files.exists(Path.of("missing.txt")));
}
}
Ada -> 92
Linus -> 85
Grace -> 97
Average: 91.33
Ada 92
Linus 85
Grace 97
3 lines, first = Ada 92
19 bytes
15 chars
false
The last lines show something important: "Héllo, wörld ✓\n" is 15 characters but 19 bytes on disk. é and ö take two bytes each in UTF-8, and ✓ takes three. Which brings us to encodings.
The Modern Files Methods
For small and medium files, the java.nio.file.Files class offers one-line operations that are often simpler than Scanner/PrintWriter:
| Method | What it does |
|---|---|
Files.readString(path) 11 | the whole file as one String |
Files.readAllLines(path) 8 (7 with a Charset argument) | a List<String>, one element per line |
Files.lines(path) 8 | a lazy stream of lines, for very large files (close it with try-with-resources) |
Files.writeString(path, text) 11 | writes a string (creates or overwrites the file) |
Files.write(path, lines) 8 (7 with a Charset argument) | writes a list of lines |
Files.writeString(path, text, StandardOpenOption.APPEND) | appends instead of overwriting (also add CREATE if the file may not exist yet) |
Files.exists(path), Files.size(path), Files.delete(path) | check, measure, remove |
Files.newBufferedReader(path) / newBufferedWriter(path) | efficient line-by-line reading and writing |
Use Scanner when you need to parse tokens and numbers, and Files.readString/readAllLines when you just want the text. Lists (List<String>) are covered in the collections part. For now, lines.size() and lines.get(i) are all you need.
Character Encodings and UTF-8
Files store bytes, not characters. A character encoding (charset) is the rule that maps characters to bytes and back. The same text produces different bytes in different encodings, and reading a file with the wrong encoding produces garbage such as Héllo.
- UTF-8 is the dominant encoding today (used by the vast majority of web pages and source files). ASCII characters take 1 byte; others take 2–4 bytes.
- Since Java 18 (JEP 400), UTF-8 is the default for file APIs such as
Scanner(Path),PrintWriter(String)andFiles, on every operating system. Before Java 18, the default depended on the operating system's settings (for example, Windows-1252 on many Windows machines), so a program could behave differently on different computers. (TheFilesmethods have always defaulted to UTF-8.) - On older Java versions, or when a file uses another encoding, specify the charset explicitly:
import java.nio.charset.StandardCharsets;
Scanner in = new Scanner(Path.of("myfile.txt"), StandardCharsets.UTF_8);
PrintWriter out = new PrintWriter("myfile.txt", StandardCharsets.UTF_8);
String text = Files.readString(Path.of("legacy.txt"), StandardCharsets.ISO_8859_1);
Where Is My File? Relative Paths and the Working Directory
A relative path like "myfile.txt", "data/scores.txt" or "../myfile.txt" is resolved against the working directory: the directory in which the JVM was started.

- When you run
java MyProgin a terminal, it's the shell's current directory. - When you click Run in an IDE, the IDE decides: usually the project root, not the
srcfolder where your.javafile is. That's why "file not found" errors are common when beginners put data files next to their source code. (Run configurations let you change the working directory.) - You can print it:
System.out.println(System.getProperty("user.dir"));, or see where a path points withPath.of("myfile.txt").toAbsolutePath(). - An absolute path starts at the file system root (
/home/me/data/myfile.txtorc:\\data\\myfile.txt) and doesn't depend on the working directory. Avoid hard-coding absolute paths in real programs, though: they break on other machines.
No Files Needed: Shell Redirection
If you'd rather not deal with files and exceptions in a quick program, read from System.in and write to System.out as usual, and let the shell connect them to files:
java MyProg < input.txt > output.txt
< feeds input.txt to the program's standard input, and > sends standard output to output.txt (>> appends). This works on Linux, macOS and Windows. The same program can then be used interactively or with files, without any change. System.err (standard error) isn't redirected by >, so error messages still appear on the screen; redirect it with 2> if needed.
Common questions
How do I append to a file instead of overwriting it?
Use Files.writeString(path, text, StandardOpenOption.CREATE, StandardOpenOption.APPEND). With a writer, open it in append mode, for example new PrintWriter(new FileWriter("log.txt", StandardCharsets.UTF_8, true)). new PrintWriter("log.txt") always empties the file first.
Why is my output file empty?
Almost always because the PrintWriter was never closed or flushed, so the buffered text never reached the disk. Use try-with-resources. Another cause is that the file was written to a different working directory from the one you are looking in, so print Path.of("out.txt").toAbsolutePath().
Is Files.readAllLines safe for big files?
It loads the whole file into memory, which is fine for files up to a few megabytes. For large files, process them line by line with Files.lines(path) (a stream, which you should close with try-with-resources) or with Files.newBufferedReader(path) and readLine().
What should I use instead of java.io.File?
Use java.nio.file.Path and Files (Java 7, plus Path.of in Java 11). They report errors with meaningful exceptions instead of returning false, handle symbolic links and file attributes, and work with other file systems such as zip files. File is still everywhere in older APIs, and file.toPath() and path.toFile() convert between the two.
How do I read a data file that ships inside my JAR?
A file inside a JAR is a resource, not a file on disk, so Path.of can't find it. Use MyClass.class.getResourceAsStream("/data.txt") and read the returned InputStream, for example with new String(in.readAllBytes(), StandardCharsets.UTF_8).
API Reference
| Class and member | Purpose |
|---|---|
Scanner(Path p) 7 / Scanner(Path p, Charset cs) 10 | scan a file (UTF-8 by default since Java 18) |
Scanner(String data) | scan the given text (not a file name!) |
PrintWriter(String fileName) / PrintWriter(String fileName, Charset cs) 10 | write a text file |
Path.of(String first, String... more) 11 | build a path: Path.of("data", "scores.txt") |
System.getProperty("user.dir") | the working directory |
Summary
- Read files with
new Scanner(Path.of("file.txt")); nevernew Scanner("file.txt"), which scans the literal text. - Write files with
new PrintWriter("file.txt")andprint/println/printf. It creates or overwrites the file. Close it, preferably with try-with-resources. - I/O operations can throw checked
IOExceptions; declarethrows IOExceptiononmainuntil you learn exception handling. Files.readString,readAllLines,writeStringandlinesare concise modern alternatives.- Files contain bytes; the encoding maps them to characters. UTF-8 is the default since Java 18; pass
StandardCharsets.UTF_8explicitly for clarity or on older Java. - Relative paths are resolved against the working directory (
user.dir), which differs between the terminal and IDEs. - Shell redirection (
< in.txt > out.txt) lets console programs work with files unchanged.
Practice Questions
A program writes a report with a PrintWriter, but the file is empty when the program finishes. What's the most likely cause?
The writer was never closed (or flushed). PrintWriter buffers output in memory, and the buffer is only written to disk on flush()/close(). Use try-with-resources so close() always runs.
Why does this code compile only with a throws clause (or try/catch)? Scanner in = new Scanner(Path.of("data.txt"));
The Scanner(Path) constructor declares that it can throw an IOException, a checked exception. The compiler requires checked exceptions to be either caught or declared with throws in the method signature.
Your program finds "data.txt" when run from the terminal but not when run from the IDE. What's going on?
The relative path is resolved against the working directory, which differs: the terminal uses the current directory, the IDE usually uses the project root. Print System.getProperty("user.dir") to see it, move the file, or adjust the run configuration's working directory.
A file contains "Café". Read with UTF-8 it's 4 characters; how many bytes does it occupy, and what might you see if you read it as ISO-8859-1?
5 bytes: é takes two bytes in UTF-8. Read as ISO-8859-1, each byte becomes its own character, so you'd see Café (5 characters).
How do you append a line to an existing log file in one statement?
Files.writeString(Path.of("app.log"), "message\n", StandardOpenOption.CREATE, StandardOpenOption.APPEND); (import java.nio.file.StandardOpenOption). Without APPEND, writeString replaces the file's contents.
Previous: Java Console Input and Output: Scanner, Console and printf Formatting
Related reading
- Java Console Input and Output: Scanner, Console and printf Formatting
- The Java String API, Code Points, StringBuilder and Text Blocks
- Java Strings: Concatenation, Substrings, Immutability and Comparing with equals
- Java Switch Expressions: Arrow Labels, Multiple Labels, yield and case null
- Java Operators: Increment, Relational, Logical, Conditional, Bitwise and Precedence

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.