Import Java
Import Java
BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;
if (args.length > 0) {
try {
numLines = Integer.parseInt(args[0]);
if (numLines <= 0) throw new IllegalArgumentException("Number of lines must be
positive.");
} catch (NumberFormatException e) {
System.err.println("Invalid number of lines. Using default.");
}
if (args.length > 1) {
lineContent = args[1] + "\n";
}
}
if (Files.exists(Paths.get(filename))) {
Scanner scanner = new Scanner(System.in);
System.out.print("File already exists. Overwrite? (y/n): ");
if (!scanner.nextLine().equalsIgnoreCase("y")) {
System.out.println("Operation cancelled.");
return;
}
}
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
Problem 1: EnhancedLineCounter.java
Objective:
Count total lines, empty lines, and words in a text file. Handle errors gracefully and work
efficiently.
Problems Solved:
Counts Lines: lineCount++ inside the loop.
Error Handling:
Efficiency: Uses BufferedReader to read line by line (no full-file memory loading).
Changes Made:
Added if (args.length != 1) check for proper usage.
Wrapped file reading in try-with-resources for safe resource management.
Problem 2: EfficientBufferedWriter.java
Objective:
Write a large number of lines to a file efficiently, with progress tracking and user customization.
Problems Solved:
Efficient Buffering:
Progress Indication:
java
Copy code
if (i % (numLines / 10) == 0)
Custom Line Content:
Changes Made:
Added default line formatting with %d.
Problems Solved:
Write CSV File:
Buffered Writing:
Changes Made:
Structured the Student class as static and self-contained.