Skip to content
Java project #11Intermediate

Student Records (CRUD with File Storage)

Create, read, update and delete student records with validation, sorting, branch statistics and safe persistence to a CSV file between runs.

Estimated time
~5 hours to build
Files
7 files · 429 lines
Technologies
Java 21, Records with compact constructors, java.nio.file (Files, Path, StandardCopyOption), Collectors.summarizingDouble

Introduction

CRUD — create, read, update, delete — is the backbone of most business software. This project builds it in layers: an immutable Student record that validates itself, a StudentRepository that stores records and saves them to disk safely, and a command interface on top.

Problem statement

Manage student records (roll number, name, branch, year 1–4 and CGPA 0–10) stored in data/students.csv. On start-up load the file, skipping and reporting damaged lines. Support adding (rejecting duplicates and invalid data), showing, updating CGPA, promoting to the next year (not beyond year 4), deleting, listing sorted by roll, name or CGPA, filtering by branch, statistics per branch, saving and reloading. Warn when quitting with unsaved changes.

Objectives

  • Implement CRUD operations behind a repository interface
  • Read and write CSV with java.nio.file
  • Save atomically using a temporary file and a move
  • Model updates on an immutable record with 'wither' methods

Features

  • Validated, normalised records (branch upper-cased, names trimmed)
  • Tolerant loading with warnings
  • Sorting, filtering and per-branch statistics
  • Atomic save, reload, and an unsaved-changes warning

Concepts demonstrated

  • CRUD
  • Repository pattern
  • Persistence
  • Atomic writes
  • Immutability

System architecture

Student is a record whose compact constructor validates and normalises fields; toCsv/fromCsv convert to and from text, and withCgpa/promoted return modified copies. StudentRepository keeps a TreeMap<Integer, Student>; load reads the file and collects warnings for bad lines; save writes a header and every record to students.csv.tmp and then moves it over the real file, so an interrupted save can't corrupt the data. Main tracks whether there are unsaved changes.

TextArchitecture diagram
Main --(commands)--> StudentRepository --(load/save)--> data/students.csv
|
TreeMap<roll, Student> (immutable records)

Folder structure

TextProject tree
student-records-crud/
├── README.md
├── data/students.csv
├── src/Main.java
├── src/Student.java
├── src/StudentRepository.java
├── tests/expected-output.txt
└── tests/sample-input.txt

Complete source code

src/Main.java

118 lines
Javasrc/Main.java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Comparator;
import java.util.DoubleSummaryStatistics;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;
import java.util.stream.Collectors;
/**
* Student Records (CRUD) — create, read, update and delete student records, with search,
* sorting, branch statistics and persistence to data/students.csv between runs.
*
* Commands:
* add ROLL, NAME, BRANCH, YEAR, CGPA show ROLL cgpa ROLL VALUE promote ROLL
* delete ROLL list [roll|name|cgpa] branch CODE stats save reload quit
*/
public class Main {
public static void main(String[] args) throws IOException {
Path file = Path.of("data", "students.csv");
Files.createDirectories(file.getParent());
StudentRepository repo = new StudentRepository(file);
List<String> warnings = repo.load();
System.out.println("=== Student Records === loaded " + repo.all().size() + " record(s) from " + file.toString().replace('\\', '/'));
warnings.forEach(w -> System.out.println(" warning: " + w));
Scanner in = new Scanner(System.in);
boolean dirty = false;
while (true) {
System.out.print("> ");
if (!in.hasNextLine()) break;
String line = in.nextLine().trim();
System.out.println();
if (line.isEmpty()) continue;
String cmd = line.split("\\s+")[0].toLowerCase();
String rest = line.substring(cmd.length()).trim();
String[] w = rest.isEmpty() ? new String[0] : rest.split("\\s+");
try {
switch (cmd) {
case "add" -> {
Student s = Student.fromCsv(rest);
repo.create(s);
dirty = true;
System.out.println("Created " + s.roll() + " " + s.name());
}
case "show" -> System.out.println(repo.read(Integer.parseInt(rest)).map(Main::describe).orElse("No student with roll " + rest));
case "cgpa" -> {
Student s = repo.read(Integer.parseInt(w[0])).orElseThrow(() -> new IllegalArgumentException("no student with roll " + w[0]));
repo.update(s.withCgpa(Double.parseDouble(w[1])));
dirty = true;
System.out.println("Updated " + s.name() + ": CGPA " + s.cgpa() + " -> " + w[1]);
}
case "promote" -> {
Student s = repo.read(Integer.parseInt(rest)).orElseThrow(() -> new IllegalArgumentException("no student with roll " + rest));
repo.update(s.promoted());
dirty = true;
System.out.println(s.name() + " promoted to year " + (s.year() + 1));
}
case "delete" -> {
Student s = repo.delete(Integer.parseInt(rest));
dirty = true;
System.out.println("Deleted " + s.roll() + " " + s.name());
}
case "list" -> {
Comparator<Student> order = switch (rest.isEmpty() ? "roll" : rest) {
case "roll" -> Comparator.comparingInt(Student::roll);
case "name" -> Comparator.comparing(Student::name);
case "cgpa" -> Comparator.comparingDouble(Student::cgpa).reversed().thenComparingInt(Student::roll);
default -> throw new IllegalArgumentException("list by roll, name or cgpa");
};
print(repo.all().stream().sorted(order).toList());
}
case "branch" -> print(repo.all().stream().filter(s -> s.branch().equalsIgnoreCase(rest)).toList());
case "stats" -> stats(repo);
case "save" -> {
repo.save();
dirty = false;
System.out.println("Saved " + repo.all().size() + " record(s)");
}
case "reload" -> {
repo.load();
dirty = false;
System.out.println("Reloaded " + repo.all().size() + " record(s) from disk (unsaved changes discarded)");
}
case "quit" -> {
if (dirty) System.out.println("Warning: quitting with unsaved changes");
return;
}
default -> System.out.println("Commands: add show cgpa promote delete list branch stats save reload quit");
}
} catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
System.out.println("Error: missing or invalid number");
} catch (IllegalArgumentException | IllegalStateException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
static String describe(Student s) {
return String.format("%d %-12s %-4s year %d CGPA %.2f", s.roll(), s.name(), s.branch(), s.year(), s.cgpa());
}
static void print(List<Student> list) {
if (list.isEmpty()) System.out.println(" (none)");
list.forEach(s -> System.out.println(" " + describe(s)));
}
static void stats(StudentRepository repo) {
Map<String, DoubleSummaryStatistics> byBranch = repo.all().stream()
.collect(Collectors.groupingBy(Student::branch, TreeMap::new, Collectors.summarizingDouble(Student::cgpa)));
byBranch.forEach((b, st) -> System.out.printf(" %-4s %d student(s), average CGPA %.2f, best %.2f%n", b, st.getCount(), st.getAverage(), st.getMax()));
long distinction = repo.all().stream().filter(s -> s.cgpa() >= 8.5).count();
System.out.println(" CGPA 8.5 or above: " + distinction);
}
}

What each file does

src/Student.java
The validated, immutable student record and its CSV conversion.
src/StudentRepository.java
In-memory storage keyed by roll number, tolerant loading and atomic saving.
src/Main.java
The command loop, listing, filtering and statistics.

How to run it

Compile

Terminal
javac -d out $(find src -name "*.java")
# Windows PowerShell: javac -d out (Get-ChildItem -Recurse src -Filter *.java).FullName

Run

Terminal
java -cp out Main

Test against the expected output

Terminal
java -cp out Main < tests/sample-input.txt > actual.txt
diff actual.txt tests/expected-output.txt
# Windows PowerShell:
# Get-Content tests\sample-input.txt | java -cp out Main > actual.txt

Expected output

Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.

Texttests/expected-output.txt
=== Student Records === loaded 4 record(s) from data/students.csv
warning: line 5 skipped: expected 5 fields: 104,broken line
>
101 Asha Rao CSE year 2 CGPA 8.90
102 Ravi Kumar ECE year 3 CGPA 7.45
103 Meera Iyer CSE year 1 CGPA 9.20
105 John Mathew MECH year 4 CGPA 6.80
>
Created 106 Priya Shah
>
Error: roll 101 already exists
>
Error: branch must be 2-4 letters, e.g. CSE
>
Error: year must be 1-4
>
103 Meera Iyer CSE year 1 CGPA 9.20
>
No student with roll 999
>
Updated Ravi Kumar: CGPA 7.45 -> 8.10
>
Error: CGPA must be between 0 and 10
>
Error: John Mathew is already in final year
>
Meera Iyer promoted to year 2
>
Deleted 106 Priya Shah
>
Error: no student with roll 106
>
Created 106 Priya Shah
>
103 Meera Iyer CSE year 2 CGPA 9.20
101 Asha Rao CSE year 2 CGPA 8.90
106 Priya Shah CSE year 2 CGPA 8.60
102 Ravi Kumar ECE year 3 CGPA 8.10
105 John Mathew MECH year 4 CGPA 6.80
>
101 Asha Rao CSE year 2 CGPA 8.90
103 Meera Iyer CSE year 2 CGPA 9.20
106 Priya Shah CSE year 2 CGPA 8.60
>
CSE 3 student(s), average CGPA 8.90, best 9.20
ECE 1 student(s), average CGPA 8.10, best 8.10
MECH 1 student(s), average CGPA 6.80, best 6.80
CGPA 8.5 or above: 3
>
Saved 5 record(s)
>
Updated Asha Rao: CGPA 8.9 -> 4.00
>
Reloaded 5 record(s) from disk (unsaved changes discarded)
>
101 Asha Rao CSE year 2 CGPA 8.90
>
Input
list
add 106, Priya Shah, cse, 2, 8.55
add 101, Duplicate, CSE, 1, 5
add 107, Kiran, Civil Eng, 1, 7
add 108, Lina, IT, 5, 8
show 103
show 999
cgpa 102 8.10
cgpa 102 11
promote 105
promote 103
delete 106
delete 106
add 106, Priya Shah, CSE, 2, 8.60
list cgpa
branch cse
stats
save
cgpa 101 4.00
reload
show 101
quit

Testing

  • Run from the project folder with tests/sample-input.txt and compare with tests/expected-output.txt.
  • The sample data file contains a damaged line (104,broken line), which is reported and skipped.
  • Changing Asha's CGPA after save and then running reload restores the saved value 8.90.
  • Note: running the sample session saves to data/students.csv; restore it from the download (or git) to rerun the test exactly.

Common errors

NumberFormatException while loading

Parse each line inside try/catch and report the line number, as load() does, instead of aborting.

The data file is empty after a crash

Write to a temporary file first and move it into place only when the write succeeded.

Possible improvements

  • Add an undo of the last change
  • Export reports as CSV
  • Replace the file with an SQLite database via JDBC

Additional challenges

  1. 1Add search by name prefix.
  2. 2Keep a history of CGPA changes per student.
  3. 3Support importing another CSV file and merging duplicates.

Built and tested it yourself? Mark it to update your dashboard.