Skip to main content

Lesson 7 of 8

Mini Project: Library System - Part 7 (File I/O)

Add file persistence to the Library System - save and load the catalog from a CSV file, export borrow records to a formatted report, load configuration from a properties file with dev/prod profile support, and watch an import directory for new CSVs.

20 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

File-Backed Catalog

File-Backed Catalog
import java.io.*;
import java.nio.file.*;
import java.util.*;

public class CatalogStore {
    private static final String HEADER = "isbn,title,author,price,available";
    private final Path filePath;

    public CatalogStore(Path filePath) {
        this.filePath = filePath;
    }

    public void save(Collection<Book> books) throws IOException {
        Files.createDirectories(filePath.getParent());
        try (BufferedWriter writer = Files.newBufferedWriter(filePath)) {
            writer.write(HEADER);
            writer.newLine();
            for (Book b : books) {
                writer.write(String.format("%s,%s,%s,%.2f,%b",
                    b.getIsbn(), quote(b.getTitle()), quote(b.getAuthor()),
                    b.getPrice(), b.isAvailable()));
                writer.newLine();
            }
        }
        System.out.println("Catalog saved: " + filePath + " (" + books.size() + " books)");
    }

    public List<Book> load() throws IOException {
        if (!Files.exists(filePath)) return new ArrayList<>();
        List<Book> books = new ArrayList<>();
        try (var lines = Files.lines(filePath)) {
            lines.skip(1)               // skip header
                 .filter(l -> !l.isBlank())
                 .forEach(line -> {
                     try {
                         books.add(parseLine(line));
                     } catch (Exception e) {
                         System.err.println("Skipping bad line: " + line);
                     }
                 });
        }
        System.out.println("Loaded " + books.size() + " books from " + filePath);
        return books;
    }

    public void exportReport(List<BorrowRecord> records, Path reportFile) throws IOException {
        try (PrintWriter pw = new PrintWriter(Files.newBufferedWriter(reportFile))) {
            pw.println("╔══════════════════════════════════════════════════╗");
            pw.println("║            BORROW HISTORY REPORT                ║");
            pw.println("╠══════════════════════════════════════════════════╣");
            pw.printf("║ %-20s %-15s %10s ║%n", "Book", "Member", "Due Date");
            pw.println("╠══════════════════════════════════════════════════╣");
            for (BorrowRecord r : records) {
                pw.printf("║ %-20s %-15s %10s ║%n",
                    truncate(r.getBook().getTitle(), 20),
                    truncate(r.getMemberId(), 15),
                    r.getDueDate().toString());
            }
            pw.println("╚══════════════════════════════════════════════════╝");
        }
        System.out.println("Report written: " + reportFile);
    }

    private Book parseLine(String line) {
        String[] p = line.split(",", 5);
        Book b = new Book(p[0], dequote(p[1]), dequote(p[2]), Double.parseDouble(p[3]));
        if ("false".equals(p[4])) b.borrow();
        return b;
    }

    private String quote(String s)   { return s.contains(",") ? "\"" + s + "\"" : s; }
    private String dequote(String s) { return s.startsWith("\"") ? s.substring(1, s.length()-1) : s; }
    private String truncate(String s, int len) { return s.length() <= len ? s : s.substring(0, len-3) + "..."; }
}

Quick Quiz

Tip

Tip

Practice Mini Project Library System Part 7 File IO in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and concepts for Mini Project: Library System - Part 7 (File I/O)

Practice Task

Note

Practice Task - (1) Write a working example of Mini Project Library System Part 7 File IO from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Common Mistake

Warning

A common mistake with Mini Project Library System Part 7 File IO is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready java code.

Topics in This Module

0/8 done