java · level 2 · unit 7 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Save one record per line, then each line into parts.
A file of books works best with one book per line, like Holes,Louis Sachar,1998. That layout is called , comma-separated values. Files.write(path, lines) saves a list of strings, one per line, and gives them back as a List<String>.
line.split(",") cuts a line into an array wherever a comma appears: parts[0] is the title and parts[2] the year. Every part is text, so use Integer.parseInt when you need a number. Now each line can become data again.
import java.io.IOException;
import java.nio.file.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
Path path = Path.of("books.csv");
Files.write(path, List.of("Holes,Louis Sachar,1998", "Matilda,Roald Dahl,1988"));
List<String> lines = Files.readAllLines(path);
System.out.println(lines.size() + " books");
for (String line : lines) {
String[] parts = line.split(",");
System.out.println(parts[0] + " (" + parts[2] + ") by " + parts[1]);
}
}
} List<String> works like the lists you know, because ArrayList is one kind of List.
guess first
Split a line of scores. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
public class Main {
public static void main(String[] args) {
String line = "Ava,7,9,8";
String[] parts = line.split(",");
int total = 0;
for (int i = 1; i < parts.length; i++) {
total = total + Integer.parseInt(parts[i]);
}
System.out.println(parts.length + " parts, " + parts[0] + " scored " + total);
}
}
your turn
Your turn. Save your pets.
Add a pet of your own on line 7, in the same layout: a name, a comma and an age. Then press run to save the list and read it back.
output
press run to see what happens
fix it
The fruit count crashed. Fix it!
output
press run to see what happens
- Java stopped with an
ArrayIndexOutOfBoundsExceptionon line 11. How many parts did the split make? - The lines have no spaces, so splitting at a space leaves one whole part. The parts are separated by commas.
- Change
split(" ")tosplit(",")on line 10, then press run.
nailed it
you turned lines back into records. :D
- Save one record per line, with commas between the parts.
Files.readAllLinesgives back aList<String>.split(",")cuts a line into parts.
new words in your collection
- CSV
- readAllLines
- split
This lesson isn’t saved. A free account remembers every lesson you finish.