Assignment Chef icon Assignment Chef
All English tutorials

Programming lesson

Mastering File I/O in Java: A COP3330 Homework 5 Tutorial with Real-World Examples

Learn how to read and write files in Java using Scanner and PrintWriter. This tutorial covers parsing CSV-like data, counting online classes, and generating a filtered text file—perfect for COP3330 Homework 5.

Java file I/O Scanner Java PrintWriter Java COP3330 homework 5 read CSV file Java write text file Java online classes count classroom search Java Java programming tutorial file parsing Java Java try-with-resources data processing Java school project Java file handling examples Java for beginners CSV parsing Java

Introduction to File I/O in Java

File Input/Output (I/O) is a fundamental skill in Java programming. Whether you're building a school project, a game leaderboard, or a data processing app, reading from and writing to files is essential. In this tutorial, we'll tackle a typical COP3330 assignment: parsing a course catalog file (lec.txt), counting online classes, finding classrooms, and creating a filtered file (lecturesOnly.txt). We'll use Scanner for reading and PrintWriter for writing. By the end, you'll be able to handle real-world data like a pro.

Understanding the Input File Format

Your lec.txt contains lines like:
89745,COT6578,Advanced Computer theory,Graduate,F2F,PSY-108,No
Each line represents a lecture or lab. Lectures have 7 fields: CRN, course code, title, level, modality, room, and lab indicator ("Yes" or "No"). If the modality is "Online", the line ends after 5 fields. Labs are listed on separate lines after a lecture with labs. For example:
69745,COP5698, Programming Languages,Graduate,F2F,CB2-122,YES
19745,MSB-123
Here, the lecture has three labs (each with CRN and room). Your program must parse these correctly.

Step 1: Reading the File with Scanner

First, create a Scanner object to read lec.txt. Use a try-with-resources block to ensure the file is closed automatically.

try (Scanner sc = new Scanner(new File("lec.txt"))) {
    while (sc.hasNextLine()) {
        String line = sc.nextLine();
        // process line
    }
} catch (FileNotFoundException e) {
    System.out.println("File not found.");
}

Each line is a comma-separated string. Use line.split(",") to get fields. Check the number of fields: if 5 or 7, it's a lecture; if 2, it's a lab.

Step 2: Counting Online Classes

Online lectures have only 5 fields (no room or lab indicator). Count them as you read. For example, if fields length == 5 and fields[3].equalsIgnoreCase("Online"), increment a counter.

int onlineCount = 0;
if (fields.length == 5 && fields[3].equalsIgnoreCase("Online")) {
    onlineCount++;
}

Display the total: System.out.println("There are " + onlineCount + " online lectures offered.");

Step 3: Finding Lectures and Labs by Classroom

Ask the user for a classroom (e.g., "MSB-123"). Then, scan the file again (or store data in lists) to find all CRNs (lectures and labs) held in that room. For lectures, check fields[5] (room). For labs, fields[1] is the room. Print the CRNs.

System.out.print("Enter the classroom: ");
String room = scanner.nextLine();
// During second pass, if (fields.length == 7 && fields[5].equals(room)) print fields[0];
// If fields.length == 2 && fields[1].equals(room)) print fields[0];

Step 4: Creating lecturesOnly.txt

This file lists all online lectures and lectures with no lab. Online lectures have 5 fields; no-lab lectures have 7 fields with the last field being "No". Use PrintWriter to write each qualifying line.

try (PrintWriter pw = new PrintWriter("lecturesOnly.txt")) {
    // During reading, if (fields.length == 5 || (fields.length == 7 && fields[6].equalsIgnoreCase("No"))) {
        pw.println(line);
    }
}

Add headers: "Online Lectures" and "Lectures with No Lab". You can group them by writing all online first, then no-lab.

Putting It All Together

Combine the steps. Use a single pass to count online and store lines for later writing? Or two passes? For simplicity, read once into lists, then process. Here's a skeleton:

import java.util.*;
import java.io.*;

public class FileIOHomework {
    public static void main(String[] args) throws FileNotFoundException {
        List<String> allLines = new ArrayList<>();
        List<String> onlineLines = new ArrayList<>();
        List<String> noLabLines = new ArrayList<>();
        int onlineCount = 0;
        
        try (Scanner sc = new Scanner(new File("lec.txt"))) {
            while (sc.hasNextLine()) {
                String line = sc.nextLine();
                allLines.add(line);
                String[] parts = line.split(",");
                if (parts.length == 5 && parts[3].equalsIgnoreCase("Online")) {
                    onlineCount++;
                    onlineLines.add(line);
                } else if (parts.length == 7 && parts[6].equalsIgnoreCase("No")) {
                    noLabLines.add(line);
                }
            }
        }
        System.out.println("There are " + onlineCount + " online lectures offered.");
        
        Scanner input = new Scanner(System.in);
        System.out.print("Enter the classroom: ");
        String room = input.nextLine();
        System.out.print("The crns held in " + room + " are: ");
        for (String line : allLines) {
            String[] parts = line.split(",");
            if (parts.length == 7 && parts[5].equals(room)) {
                System.out.print(parts[0] + " ");
            } else if (parts.length == 2 && parts[1].equals(room)) {
                System.out.print(parts[0] + " ");
            }
        }
        System.out.println();
        
        try (PrintWriter pw = new PrintWriter("lecturesOnly.txt")) {
            pw.println("Online Lectures");
            for (String line : onlineLines) pw.println(line);
            pw.println("Lectures with No Lab");
            for (String line : noLabLines) pw.println(line);
        }
        System.out.println("lecturesOnly.txt is created");
        System.out.println("Goodbye!");
    }
}

Why This Matters: Real-World Analogy

Think of this like organizing a college course registration system similar to what universities use. Or imagine you're building a backend for a gaming tournament where each player's stats are stored in CSV files. File I/O lets you read leaderboards, update scores, and generate reports. In the age of AI and data science, parsing text files is a stepping stone to handling large datasets.

Common Pitfalls

  • FileNotFoundException: Always use try-catch or declare throws.
  • Empty lines: Check line.isEmpty() before splitting.
  • Case sensitivity: Use equalsIgnoreCase for "Online".
  • Extra spaces: Trim fields if needed.

Testing Your Program

Use the sample input from your assignment. For example, if lec.txt contains the given lines, your output should match the sample run. Make sure lecturesOnly.txt is formatted exactly as shown.

Conclusion

You've learned how to read and write files in Java, parse structured data, and generate filtered output. This skill is used in data processing, web development, and automation. Next time you're working on a project—whether it's a school grade tracker or a fantasy sports app—you'll know exactly how to handle file I/O. Good luck with your COP3330 homework!