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 redViolets are blueJava reads filesAnd so can you
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
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.