Part 07 / Stage 1
Packages, I/O and build basics
Goal: Organize a program into packages that match its folder structure, compile and run a multi-file program with plain
javac/java, and read and write text files safely withjava.nio.fileand try-with-resources. Time: ~5 hours
What you will learn
- Why packages exist, and the package declaration (
package billing;) - The one hard rule: folder structure must match the package's dots
- Compiling several files (across several packages) in one
javaccall, with-dto choose where the.classfiles go - Running a compiled program with
java -cp(the classpath: wherejavalooks for.classfiles) - Reading and writing whole files and lists of lines with
java.nio.file.FilesandPath try-with-resourceswith real I/O resources (BufferedReader/BufferedWriter), including more than one resource in the sametry- Handling a missing file as a normal, caught
IOExceptioninstead of a crash - Building a to-do list that survives between runs, and a log parser, as two small multi-file, packaged programs
ℹ️ No build tool yet. Maven and Gradle appear in Stage 3 Part 15. Everything here uses only
javacandjava, exactly like Parts 1–6 — you are learning what a build tool automates, not reaching for one yet.
Topics in this part
Practice
Compile every exercise with javac -d out ... and run it with java -cp out ..., exactly like the lesson. Where a program is split across packages, put each .java file in the folder its package line demands (Chapter 2). Where a program saves to a file, run it from inside its own exercise folder so the data file lands next to the source, and check the saved file's contents with cat after running.
Exercise 1: A kirana store, split into two packages
Scenario: A small Pune kirana store script has grown past one file. You split it into a store package (what a product is) and a store.util package (a helper that does not belong on the product itself).
What to do:
- In a package
store, write a classProductwith aname(String) andprice(double), a constructor, and getters. - In a package
store.util, write a classDiscountwith onestaticmethodapplyDiscount(double price, double percent)that returns the price after taking off that percentage. - In a
Mainclass with no package, createProducts for"Rice 5kg"(₹180),"Dal 1kg"(₹140) and"Ghee 1kg"(₹650). Print the first two withSystem.out.printf("%s: ₹%.2f%n", ...). Print Ghee's price before and after a 10% Diwali discount (viaDiscount.applyDiscount), each with the sameprintfstyle plus a short label.
Sample output:
Rice 5kg: ₹180.00
Dal 1kg: ₹140.00
Ghee 1kg: ₹650.00 (before Diwali discount)
Ghee 1kg: ₹585.00 (after 10% Diwali discount)
💡 Hint: Folder layout: store/Product.java, store/util/Discount.java, Main.java. Compile all three in one javac -d out call, then run with java -cp out Main.
Exercise 2: A shopping list, written and read back
Scenario: Before a Pune store run, you want the list saved to a file, not just printed. What to do:
- Build a
List<String>of items:"Rice","Dal","Sugar","Tea powder". - Write it to
shopping.txtwithFiles.write, then print how many items were written. - Read the file back with
Files.readAllLinesand print the count again, then every item as"<number>. <item>".
Sample output:
Wrote 4 items to shopping.txt
Items in shopping.txt: 4
1. Rice
2. Dal
3. Sugar
4. Tea powder
💡 Hint: Files.write(path, someList) takes any List<String> — List.of(...) works directly.
Exercise 3: A visit log that grows across runs
Scenario: A shop wants to count how many times this program has been run — once per customer visit — without keeping anything in memory, since each visit is a separate run of the program. What to do:
- If
visits.txtexists, the next visit number is its current line count + 1; otherwise it is1. - Using
try-with-resourceswith aBufferedWriteropened withStandardOpenOption.CREATEandStandardOpenOption.APPEND, write one line:"Visit #<n> recorded". - Print
"Recorded visit #<n>"and then the total line count in the file after writing. - Run the program three times in a row and show the final content of
visits.txt.
Sample output (three runs, one after another):
Recorded visit #1
Total visits so far: 1
Recorded visit #2
Total visits so far: 2
Recorded visit #3
Total visits so far: 3
visits.txt after all three runs:
Visit #1 recorded
Visit #2 recorded
Visit #3 recorded
💡 Hint: Files.exists(LOG) ? Files.readAllLines(LOG).size() + 1 : 1 gives the next visit number in one line.
Exercise 4: An attendance register that survives a missing file
Scenario: A class register is a simple name,status text file. Sometimes the file for a given day hasn't been created yet, and the program must say so instead of crashing.
What to do:
- Starting data, saved as
attendance.txt:Asha,Present Ravi,Absent Meera,Present Kiran,Present Priya,Absent - Write a method that opens a given file with
try-with-resources+BufferedReader, countsPresentvsAbsent, and prints"<file> -> present: <p>, absent: <a>". - Call it once for
attendance.txt, and once for a file that does not exist,roll2.txt. The second call must not crash — catch theIOExceptionand print"<file> -> could not read register: <message>".
Sample output:
attendance.txt -> present: 3, absent: 2
roll2.txt -> could not read register: roll2.txt
💡 Hint: e.getMessage() on a NoSuchFileException is just the path that was missing.
Exercise 5: A mini habit tracker — add and list only
Scenario: Before building the full habit tracker in Exercise 7, start with the smallest useful slice: record habit names and list them back, saved to a file, in a package of their own. What to do:
- In a package
habittrackermini, write a classHabitTrackerMiniwhosemainreads its command fromargs[0]. add <name...>(join the rest ofargswith spaces) appends a new habit name tohabits.txtand prints"Added habit: <name>".listprints every saved habit as"<number>. <name>", or"No habits yet."if the file is empty or missing.- Run
addtwice, thenlist.
Sample output:
Added habit: Drink 2L water
Added habit: Walk 5000 steps
1. Drink 2L water
2. Walk 5000 steps
💡 Hint: Load the existing lines (or an empty list if the file doesn't exist yet) before adding the new one, then write the whole list back with Files.write.
Exercise 6: Transaction totals by city
Scenario: A payments file lists city,amount on every line. You want one total per city, printed in a fixed, predictable order — not whatever order a HashMap happens to use.
What to do:
- Starting data, saved as
transactions.txt:Pune,1200 Delhi,800 Pune,650 Mumbai,2200 Delhi,400 Pune,300 Mumbai,500 - Read the file with
try-with-resources+BufferedReader, and add each amount into aMap<String, Double>keyed by city (getOrDefault+ put, as in the lesson'sLogParser). - Print the total for
"Pune","Delhi","Mumbai"in that exact order, formatted"<city>: ₹%.2f".
Sample output:
Pune: ₹2150.00
Delhi: ₹1200.00
Mumbai: ₹2700.00
💡 Hint: Loop over new String[] {"Pune", "Delhi", "Mumbai"}, not over the map's own keys — that is what makes the order fixed.
Exercise 7: A full habit tracker with streaks
Scenario: Turn Exercise 5 into the real thing: a habit tracker that also tracks a day-streak per habit, and can remove a habit, all saved to a text file. What to do:
- In a package
habittracker, write a classHabitwithnameand a mutablestreak(starts at0), a methodextendStreak()that adds one,toLine()/fromLine(String)for saving as"<name>|<streak>", and atoString()like"Walk 5000 steps - streak: 3 days"(singular"1 day"for exactly 1). - In
HabitTracker, support four commands viaargs[0]:add <name...>,list,done <number>(callsextendStreak()on that habit and prints the new streak),remove <number>. - Persist with
Files.readAllLines/Files.writetohabits.txt, exactly like the lesson'sTodoApp. - Run this sequence: add three habits, list, mark habit 1 done twice and habit 2 done once, list again, remove habit 3, list a final time. Show
habits.txtat the end.
Sample output:
Added habit: Drink 2L water
Added habit: Walk 5000 steps
Added habit: Read 10 pages
1. Drink 2L water - streak: 0 days
2. Walk 5000 steps - streak: 0 days
3. Read 10 pages - streak: 0 days
Marked today done for: Drink 2L water (streak now 1)
Marked today done for: Drink 2L water (streak now 2)
Marked today done for: Walk 5000 steps (streak now 1)
1. Drink 2L water - streak: 2 days
2. Walk 5000 steps - streak: 1 day
3. Read 10 pages - streak: 0 days
Removed: Read 10 pages
1. Drink 2L water - streak: 2 days
2. Walk 5000 steps - streak: 1 day
habits.txt at the end:
Drink 2L water|2
Walk 5000 steps|1
💡 Hint: This is the lesson's TodoApp/Task pattern with a counter instead of a boolean — reuse the same load/save shape.
Exercise 8: A pipe-separated access log, with a written report
Scenario: A web app's access log uses | instead of spaces, and this time you must also write a summary file, not just print one.
What to do:
- Starting data, saved as
accesslog/access.log(date|time|status|path|user):2026-11-21|10:02:11|200|/orders|Asha 2026-11-21|10:02:45|200|/menu|Ravi 2026-11-21|10:03:02|404|/offers|Meera 2026-11-21|10:03:40|200|/orders|Asha 2026-11-21|10:04:15|500|/payment|Ravi 2026-11-21|10:05:02|200|/menu|Kiran 2026-11-21|10:05:47|500|/payment|Asha 2026-11-21|10:06:10|200|/orders|Priya 2026-11-21|10:06:55|404|/support|Ravi - In a package
accesslog, writeAccessLogParser: read the log withtry-with-resources+BufferedReader, split each line on\|, count lines per status code, and print every500line as it is found, under a"---- 500 errors ----"heading. - Write a report to
accesslog/status-report.txtwithtry-with-resources+BufferedWriter: one line per status,"<status>: <count>", for200,404,500in that order. - Read the report back and print it under a
"---- accesslog/status-report.txt ----"heading, so the program proves what it wrote.
Sample output:
---- 500 errors ----
2026-11-21|10:04:15|500|/payment|Ravi
2026-11-21|10:05:47|500|/payment|Asha
---- accesslog/status-report.txt ----
200: 5
404: 2
500: 2
💡 Hint: line.split("\\|") — | is a regex special character, so it needs the backslash-escaped form inside split.
Show the solutions for Part 7 (14 files)
solutions/ex01-kirana-packages/Main.java
import store.Product;
import store.util.Discount;
public class Main {
public static void main(String[] args) {
Product rice = new Product("Rice 5kg", 180);
Product dal = new Product("Dal 1kg", 140);
Product ghee = new Product("Ghee 1kg", 650);
System.out.printf("%s: ₹%.2f%n", rice.getName(), rice.getPrice());
System.out.printf("%s: ₹%.2f%n", dal.getName(), dal.getPrice());
double discounted = Discount.applyDiscount(ghee.getPrice(), 10);
System.out.printf("%s: ₹%.2f (before Diwali discount)%n", ghee.getName(), ghee.getPrice());
System.out.printf("%s: ₹%.2f (after 10%% Diwali discount)%n", ghee.getName(), discounted);
}
}
solutions/ex01-kirana-packages/store/Product.java
package store;
public class Product {
private final String name;
private final double price;
public Product(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
}
solutions/ex01-kirana-packages/store/util/Discount.java
package store.util;
public class Discount {
public static double applyDiscount(double price, double percent) {
return price - (price * percent / 100);
}
}
solutions/ex02-shopping-list/ShoppingList.java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
public class ShoppingList {
public static void main(String[] args) throws IOException {
Path file = Path.of("shopping.txt");
List<String> items = List.of("Rice", "Dal", "Sugar", "Tea powder");
Files.write(file, items);
System.out.println("Wrote " + items.size() + " items to " + file);
List<String> readBack = Files.readAllLines(file);
System.out.println("Items in " + file + ": " + readBack.size());
for (int i = 0; i < readBack.size(); i++) {
System.out.println((i + 1) + ". " + readBack.get(i));
}
}
}
solutions/ex03-visit-log/VisitLog.java
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.List;
public class VisitLog {
private static final Path LOG = Path.of("visits.txt");
public static void main(String[] args) throws IOException {
int nextVisit = Files.exists(LOG) ? Files.readAllLines(LOG).size() + 1 : 1;
try (BufferedWriter writer = Files.newBufferedWriter(
LOG, StandardOpenOption.CREATE, StandardOpenOption.APPEND)) {
writer.write("Visit #" + nextVisit + " recorded");
writer.newLine();
}
System.out.println("Recorded visit #" + nextVisit);
List<String> allVisits = Files.readAllLines(LOG);
System.out.println("Total visits so far: " + allVisits.size());
}
}
solutions/ex04-attendance-reader/attendance.txt
Asha,Present
Ravi,Absent
Meera,Present
Kiran,Present
Priya,Absent
solutions/ex04-attendance-reader/AttendanceReader.java
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class AttendanceReader {
public static void main(String[] args) {
printAttendance(Path.of("attendance.txt"));
printAttendance(Path.of("roll2.txt")); // does not exist: must not crash
}
private static void printAttendance(Path file) {
int present = 0;
int absent = 0;
try (BufferedReader reader = Files.newBufferedReader(file)) {
String line;
while ((line = reader.readLine()) != null) {
if (line.isBlank()) {
continue;
}
String[] parts = line.split(",");
if (parts[1].equals("Present")) {
present++;
} else {
absent++;
}
}
System.out.println(file + " -> present: " + present + ", absent: " + absent);
} catch (IOException e) {
System.out.println(file + " -> could not read register: " + e.getMessage());
}
}
}
solutions/ex05-habit-tracker-mini/habittrackermini/HabitTrackerMini.java
package habittrackermini;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class HabitTrackerMini {
private static final Path STORE = Path.of("habits.txt");
public static void main(String[] args) throws IOException {
if (args.length == 0) {
System.out.println("Usage: add <habit name> | list");
return;
}
List<String> habits = Files.exists(STORE) ? Files.readAllLines(STORE) : new ArrayList<>();
habits = new ArrayList<>(habits);
String command = args[0];
if (command.equals("add")) {
String name = String.join(" ", Arrays.asList(args).subList(1, args.length));
habits.add(name);
Files.write(STORE, habits);
System.out.println("Added habit: " + name);
} else if (command.equals("list")) {
if (habits.isEmpty()) {
System.out.println("No habits yet.");
} else {
for (int i = 0; i < habits.size(); i++) {
System.out.println((i + 1) + ". " + habits.get(i));
}
}
} else {
System.out.println("Unknown command: " + command);
}
}
}
solutions/ex06-transaction-totals/transactions.txt
Pune,1200
Delhi,800
Pune,650
Mumbai,2200
Delhi,400
Pune,300
Mumbai,500
solutions/ex06-transaction-totals/TransactionTotals.java
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
public class TransactionTotals {
public static void main(String[] args) {
Path file = Path.of("transactions.txt");
Map<String, Double> totalByCity = new HashMap<>();
try (BufferedReader reader = Files.newBufferedReader(file)) {
String line;
while ((line = reader.readLine()) != null) {
if (line.isBlank()) {
continue;
}
String[] parts = line.split(",");
String city = parts[0];
double amount = Double.parseDouble(parts[1]);
totalByCity.put(city, totalByCity.getOrDefault(city, 0.0) + amount);
}
} catch (IOException e) {
System.out.println("Could not read transactions: " + e.getMessage());
return;
}
// Print in a fixed, known order so the output never depends on HashMap's
// internal order.
for (String city : new String[] {"Pune", "Delhi", "Mumbai"}) {
System.out.printf("%s: ₹%.2f%n", city, totalByCity.getOrDefault(city, 0.0));
}
}
}
solutions/ex07-habit-tracker/habittracker/Habit.java
package habittracker;
public class Habit {
private final String name;
private int streak;
public Habit(String name, int streak) {
this.name = name;
this.streak = streak;
}
public String getName() {
return name;
}
public int getStreak() {
return streak;
}
public void extendStreak() {
streak++;
}
// One line of the save file: "Walk 5000 steps|3"
public String toLine() {
return name + "|" + streak;
}
public static Habit fromLine(String line) {
String[] parts = line.split("\\|");
return new Habit(parts[0], Integer.parseInt(parts[1]));
}
@Override
public String toString() {
return name + " - streak: " + streak + " day" + (streak == 1 ? "" : "s");
}
}
solutions/ex07-habit-tracker/habittracker/HabitTracker.java
package habittracker;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class HabitTracker {
private static final Path STORE = Path.of("habits.txt");
public static void main(String[] args) throws IOException {
if (args.length == 0) {
System.out.println("Usage: add <name> | list | done <number> | remove <number>");
return;
}
List<Habit> habits = load();
String command = args[0];
switch (command) {
case "add" -> {
String name = String.join(" ", Arrays.asList(args).subList(1, args.length));
habits.add(new Habit(name, 0));
save(habits);
System.out.println("Added habit: " + name);
}
case "list" -> printList(habits);
case "done" -> {
int index = Integer.parseInt(args[1]) - 1;
habits.get(index).extendStreak();
save(habits);
System.out.println("Marked today done for: " + habits.get(index).getName()
+ " (streak now " + habits.get(index).getStreak() + ")");
}
case "remove" -> {
int index = Integer.parseInt(args[1]) - 1;
Habit removed = habits.remove(index);
save(habits);
System.out.println("Removed: " + removed.getName());
}
default -> System.out.println("Unknown command: " + command);
}
}
private static void printList(List<Habit> habits) {
if (habits.isEmpty()) {
System.out.println("No habits yet.");
return;
}
for (int i = 0; i < habits.size(); i++) {
System.out.println((i + 1) + ". " + habits.get(i));
}
}
private static List<Habit> load() throws IOException {
if (!Files.exists(STORE)) {
return new ArrayList<>();
}
List<Habit> habits = new ArrayList<>();
for (String line : Files.readAllLines(STORE)) {
if (!line.isBlank()) {
habits.add(Habit.fromLine(line));
}
}
return habits;
}
private static void save(List<Habit> habits) throws IOException {
List<String> lines = new ArrayList<>();
for (Habit habit : habits) {
lines.add(habit.toLine());
}
Files.write(STORE, lines);
}
}
solutions/ex08-access-log-parser/accesslog/access.log
2026-11-21|10:02:11|200|/orders|Asha
2026-11-21|10:02:45|200|/menu|Ravi
2026-11-21|10:03:02|404|/offers|Meera
2026-11-21|10:03:40|200|/orders|Asha
2026-11-21|10:04:15|500|/payment|Ravi
2026-11-21|10:05:02|200|/menu|Kiran
2026-11-21|10:05:47|500|/payment|Asha
2026-11-21|10:06:10|200|/orders|Priya
2026-11-21|10:06:55|404|/support|Ravi
solutions/ex08-access-log-parser/accesslog/AccessLogParser.java
package accesslog;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
public class AccessLogParser {
public static void main(String[] args) {
Path logFile = Path.of("accesslog/access.log");
Path reportFile = Path.of("accesslog/status-report.txt");
Map<String, Integer> countByStatus = new HashMap<>();
System.out.println("---- 500 errors ----");
try (BufferedReader reader = Files.newBufferedReader(logFile)) {
String line;
while ((line = reader.readLine()) != null) {
if (line.isBlank()) {
continue;
}
// "2026-11-21|10:04:15|500|/payment|Ravi"
String[] parts = line.split("\\|");
String status = parts[2];
countByStatus.put(status, countByStatus.getOrDefault(status, 0) + 1);
if (status.equals("500")) {
System.out.println(line);
}
}
} catch (IOException e) {
System.out.println("Could not read " + logFile + ": " + e.getMessage());
return;
}
try (BufferedWriter writer = Files.newBufferedWriter(reportFile)) {
for (String status : new String[] {"200", "404", "500"}) {
String reportLine = status + ": " + countByStatus.getOrDefault(status, 0);
writer.write(reportLine);
writer.newLine();
}
} catch (IOException e) {
System.out.println("Could not write " + reportFile + ": " + e.getMessage());
return;
}
System.out.println("---- " + reportFile + " ----");
try (BufferedReader reportReader = Files.newBufferedReader(reportFile)) {
String line;
while ((line = reportReader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("Could not read report back: " + e.getMessage());
}
}
}
Common mistakes
| Mistake | Why it is wrong | Fix |
|---|---|---|
Saving a file with package billing.util; directly under billing/ instead of billing/util/ |
javac's automatic lookup (when a file isn't listed explicitly) and java's classpath lookup both translate package dots to folder slashes; a mismatch means "class/package does not exist" even though the file is on disk |
Put every .java file in a folder path that matches its package exactly |
Running with java -cp out TodoApp for a class in package todoapp; |
java needs the fully qualified name to find the .class file inside its package folder |
java -cp out todoapp.TodoApp |
Forgetting -d <folder> on javac |
.class files land next to the .java sources (still inside their package folders) instead of in one clean output folder, which gets messy fast and is easy to .gitignore incorrectly |
Always pass -d out (or similar) when compiling more than a throwaway one-file program |
Reading a whole large file with Files.readString/readAllLines |
Loads the entire file into memory at once; fine for a to-do list, wasteful or even impossible for a multi-gigabyte log | Use Files.newBufferedReader and read line by line for big files |
Opening a file without try-with-resources (or finally) |
The reader/writer stays open if an exception happens mid-way, leaking a file handle | Always open BufferedReader/BufferedWriter/any stream inside try (...) |
Assuming a HashMap's key order matches insertion order |
HashMap makes no ordering promise at all |
Loop over a fixed list/array of the keys you expect, as LogParser does |
Catching Exception instead of IOException around file code |
Hides programming mistakes (like a bad array index) under the same handler as a genuine missing-file problem | Catch the specific checked exception the I/O method actually declares |
| Treating a missing file as unrecoverable | NoSuchFileException is just another checked IOException — it is completely normal for a file to not exist yet (first run, deleted by a user) |
Catch it and decide what "not there yet" should mean for your program (empty list, create it, show a message) |
Quick recap
- A package groups related classes and avoids name collisions; state it with
package name;as the first line of the file. - The folder a
.java/.classfile lives in must match its package, dots becoming slashes —javac's automatic file lookup andjava's classpath lookup both depend on this. javac -d out A.java pkg/B.java ...compiles several files into one output folder, recreating their package subfolders;java -cp out pkg.Mainruns the result by fully qualified name.java.nio.file.Filesreads/writes whole files (readString/writeString) or lists of lines (readAllLines/write) in one call — simple, but loads everything into memory.Files.newBufferedReader/newBufferedWriterread and write line by line, and belong insidetry-with-resources, which can open more than one resource in the sametryand always closes them.- A missing file is a normal checked
IOException(NoSuchFileException), caught like any other checked exception from Part 6, not a special crash case. - A small text file is enough to make a program's data survive between runs — that is file persistence, and it is the foundation the Stage 1 project builds on.
Checklist
- I can write a package declaration and put the file in the matching folder.
- I can explain, with a real example, what breaks when the folder doesn't match the package.
- I can compile a multi-file, multi-package program with
javac -dand run it withjava -cp. - I can write and read a whole text file with
Files.writeString/readString/readAllLines/write. - I can read and write a file line by line with
try-with-resourcesandBufferedReader/BufferedWriter, including two resources in onetry. - I can catch a missing-file error without crashing the program.
- I built a to-do list that saves to a text file and survives between runs.
- I built a log parser that counts lines by level and prints the error lines.