AI Hints
Home›Java Tutorial›Writing Files, Reading Files, Practice: Save and Load
Java · Lesson 98 of 120

Reading Files

Load data from disk.

⏱ 2 min read▶ Video at 2:04:13🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Reading a file is just as easy. You can read the whole thing as one string, or as a list of lines.

  • Read it all
  • Or line by line
  • Just as easy

Two ways to read

Read string gives the whole file, as one string. Read all lines gives a list, with one string per line. Then we can loop through the lines, and number them. Run it. The poem prints, then its four lines, numbered.

Main.javajava
import java.io.IOException;
import java.nio.file.*;
import java.util.List;
public class Main {
    public static void main(String[] args) throws IOException {
        String all = Files.readString(Path.of("poem.txt"));
        System.out.print(all);
        List<String> lines = Files.readAllLines(Path.of("poem.txt"));
        System.out.println(lines.size() + " lines");
        for (int i = 0; i < lines.size(); i++) {
            System.out.println((i + 1) + ". " + lines.get(i));
        }
    }
}
Output
Roses are red
Violets are blue
Java reads files
And so can you
4 lines
1. Roses are red
2. Violets are blue
3. Java reads files
4. And so can you
Also uses poem.txt
Roses are red
Violets are blue
Java reads files
And so can you

Reading a CSV file

A CSV file stores a table, with commas between values. We read it line by line, and skip the header. Split breaks each line at the commas. Then parse int, and parse double, turn the parts into numbers. Run it. Three orders, and a total of fourteen pounds, twenty five.

Main.javajava
import java.io.IOException;
import java.nio.file.*;
public class Main {
    public static void main(String[] args) throws IOException {
        double total = 0;
        for (String line : Files.readAllLines(Path.of("orders.csv"))) {
            if (line.startsWith("item")) continue;
            String[] parts = line.split(",");
            String item = parts[0];
            int qty = Integer.parseInt(parts[1]);
            double price = Double.parseDouble(parts[2]);
            System.out.printf("%-6s %d x %.2f%n", item, qty, price);
            total += qty * price;
        }
        System.out.printf("Total: %.2f%n", total);
    }
}
Output
tea    2 x 2.50
cake   1 x 4.00
juice  3 x 1.75
Total: 14.25
Also uses orders.csv
item,qty,price
tea,2,2.50
cake,1,4.00
juice,3,1.75

Summary

Read string reads a whole file, and read all lines gives a list of lines. Split turns a CSV line into parts. Next, a practice that saves and loads data.

Key takeaways
  • Files.readString
  • Files.readAllLines
  • split(",")
Next up: Practice: Save and Load — put module eleven together