Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Java
  • Install Java 25 (JDK) and IntelliJ IDEA, Then Run Your First Program
  • Use Claude Agent, Copilot or Junie Inside IntelliJ IDEA
  • Java Hello World with Maven: What the JDK Does and What Maven Adds
  • Java Variables, Keywords and Naming Rules
  • Maven in IntelliJ: pom.xml, Dependencies and the Build Lifecycle
  • Java Primitive Types and Memory: What int x = 5 Really Does
  • Java Strings and Text Blocks: Quotes, Concatenation and parseInt
  • Java Operators: Arithmetic, a++ vs ++a, Precedence, && || and the Ternary
  • Java Type Casting: Widening, Narrowing and Converting Text to Numbers
  • Java Practice Lab: A Cafe Bill with Variables, Operators and Casting
  • Java if, else and switch: Braces, Else-If Ladders and the Modern Switch
  • Java Loops: for, while, do-while and for-each
  • Java break, continue and Nested Loops
  • What's New in Java 21 to 25: Compact Source Files and Sequenced Collections
  • Java Arrays: Indexes, Default Values, Loops and 2D Grids
  • Java Methods and Overloading: Parameters, return and Pass-by-Value
  • Java Scope, Code Blocks and the Call Stack
  • Read User Input in Java with Scanner (and the Leftover Enter Trap)
  • Java Practice Lab: A Gym Weekly Tracker with Loops, Arrays and Methods
  • Debugging Java in IntelliJ: Stack Traces, Breakpoints and a Better AI Prompt
  • Java var: Let Java Infer the Type
  • Push and Pull in IntelliJ: Two Developers, One GitHub Repository, a Rejected Push and a Conflict
  • Java Classes and Objects: One Blueprint, Many Cars
  • Java Constructors and the this Keyword
  • Java Instance Methods, Getters, Setters and toString
  • Java static: Fields, Methods and Blocks Shared by the Whole Class
  • Java Packages and Imports: Every Class Has an Address
  • Java Access Modifiers and Encapsulation: Private Data, Public Methods
  • Java final and Immutable Objects: Assign Once, Share Safely
  • Java Strings as Objects: The String Pool, == vs equals, StringBuilder and printf
  • Java Practice Lab: A Library Book Catalogue with final Fields and StringBuilder
  • Java Inheritance: extends, super and the Order Objects Are Built
  • Java Method Overriding, @Override and the Object Class
  • Java Polymorphism: Upcasting, Dynamic Dispatch and Downcasting
  • Java Composition: Has-A vs Is-A
  • Java Abstract Classes: A Parent That Leaves One Blank
  • Java Interfaces: Contracts and Multiple Inheritance
  • Java Nested, Inner and Anonymous Classes
  • Java Enums with Fields, Methods and switch
  • Java Practice Lab: Payment Processing with an Interface, an Abstract Class and an Enum
  • Java Records: A Whole Data Class in One Line
  • Java Sealed Classes and Interfaces
  • Java Pattern Matching with instanceof and switch
  • Java Record Patterns: Unpacking a Record
  • Java equals and hashCode: Why a HashSet Needs Both
  • From Arrays to Collections: The Java Collections Framework Map
  • Java Wrapper Classes and Autoboxing
  • Java ArrayList: The Stretchy Array
  • Java LinkedList vs ArrayList: Nodes or an Array
  • Java Sets: HashSet, LinkedHashSet and TreeSet
  • Java Sorting with Comparable and Comparator
  • Java Maps: HashMap, LinkedHashMap and TreeMap
  • Java Stacks, Queues and Deques: ArrayDeque and PriorityQueue
  • Choosing a Java Collection: Immutable and Sequenced Collections
  • Java Exception Handling: try, catch and finally
  • Java throw, throws, Checked vs Unchecked and Custom Exceptions
  • Java try-with-resources and Clean Error Handling
  • Java Generics: Type-Safe Containers
  • Java Generic Methods, Bounded Types and Wildcards
  • Java Lambdas and Functional Interfaces
  • Java Built-in Functional Interfaces: Predicate, Function, Consumer, Supplier
  • Java Optional: Saying Maybe Without null
  • Java Streams I: filter, map and reduce
  • Java Streams II: Collectors, groupingBy and flatMap
  • Why Concurrency: Processes, Threads and the Main Thread in Java
  • Creating Threads in Java: Thread, Runnable and Lambdas
  • Java Thread Lifecycle: sleep, join and interrupt
  • Java Race Conditions and synchronized
  • Java volatile and Atomic Variables
  • Java ExecutorService and Thread Pools
  • Java Callable, Future and CompletableFuture
  • Java Locks, Deadlock and tryLock
  • Java Concurrent Collections and Virtual Threads
  • Why Slow Work Belongs off the Request Thread: 202 Accepted and a Job Id in Spring Boot
  • Virtual Threads in Spring Boot: One Property, and the Connection Pool Trap
  • @Async, Named TaskExecutors and Structured Concurrency in Spring Boot
  • Java Files and Directories with NIO.2: Path and Files
  • Reading and Writing Text Files in Java
  • Java Structured Data: Reading and Writing JSON and CSV
  1. Blog
  2. /
  3. Java
  4. /
  5. Files and I/O

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.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Files and I/O

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
Reading a file in layers: an InputStream moves raw bytes, numbers from 0 to 255; an InputStreamReader turns bytes into characters using a charset such as UTF-8; a BufferedReader reads a big block at a time and hands out one line with readLine. filebytes 0 to 255 InputStreamraw bytes InputStreamReaderbytes to chars (UTF-8) BufferedReaderreadLine() Files.newBufferedReader(path) builds this whole stack for you, with UTF-8.
Bytes in, text out: each layer does one job.

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

JobUse
Small file, all at oncereadString, readAllLines, writeString
Big file, line by lineFiles.lines or BufferedReader in a try
Many lines to writeBufferedWriter with newLine
Words and numbersScanner
Text with accentsUTF-8 both ways

Next: files with structure, in JSON and CSV.

Keep going in Java · 78 of 79

Previous
Java Files and Directories with NIO.2: Path and Files
Next post
Java Structured Data: Reading and Writing JSON and CSV
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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.

On this page

  • Read a whole file
  • Create a file, then read it back
  • Write and read line by line
  • Read words and numbers with Scanner
  • Characters are not bytes
  • Pick the tool for the job
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.