0% found this document useful (0 votes)
5 views7 pages

Import Java

The document contains three Java programs: EnhancedLineCounter, EfficientBufferedWriter, and StudentCSVGenerator, each addressing specific file handling tasks. EnhancedLineCounter counts lines, empty lines, and words in a text file with error handling, EfficientBufferedWriter writes a large number of lines to a file with user customization and progress tracking, while StudentCSVGenerator creates a CSV file with student data. Key improvements across the programs include efficient I/O, robust error handling, and user input capabilities.

Uploaded by

labradarenz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views7 pages

Import Java

The document contains three Java programs: EnhancedLineCounter, EfficientBufferedWriter, and StudentCSVGenerator, each addressing specific file handling tasks. EnhancedLineCounter counts lines, empty lines, and words in a text file with error handling, EfficientBufferedWriter writes a large number of lines to a file with user customization and progress tracking, while StudentCSVGenerator creates a CSV file with student data. Key improvements across the programs include efficient I/O, robust error handling, and user input capabilities.

Uploaded by

labradarenz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

import java.io.

BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class EnhancedLineCounter {

public static void main(String[] args) {


if (args.length != 1) {
System.err.println("Usage: java EnhancedLineCounter <filename>");
return;
}

String filename = args[0];


int lineCount = 0;
int emptyLineCount = 0;
int wordCount = 0;

try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {


String line;
while ((line = reader.readLine()) != null) {
lineCount++;
if (line.trim().isEmpty()) {
emptyLineCount++;
} else {
String[] words = line.trim().split("\\s+");
wordCount += words.length;
}
}
} catch (NullPointerException e) {
System.err.println("Error: Filename is null.");
} catch (IOException e) {
System.err.println("Error reading file: " + e.getMessage());
}

System.out.println("Total lines: " + lineCount);


System.out.println("Empty lines: " + emptyLineCount);
System.out.println("Total words: " + wordCount);
}
}

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;

public class EfficientBufferedWriter {

public static void main(String[] args) {


String filename = "output.txt";
int numLines = 100000;
String lineContent = "Line %d\n"; // Default content

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;
}
}

try (BufferedWriter writer = new BufferedWriter(new FileWriter(filename), 8192)) {


for (int i = 0; i < numLines; i++) {
writer.write(String.format(lineContent, i + 1));
if (i % (numLines / 10) == 0) {
System.out.println(String.format("%.1f%% complete", (double) i / numLines * 100));
}
}
System.out.println("100.0% complete\nWriting completed successfully.");
} catch (IOException e) {
System.err.println("IO Error: " + e.getMessage());
} catch (IllegalArgumentException e) {
System.err.println("Error: " + e.getMessage());
} catch (Exception e) {
System.err.println("Unexpected error: " + e.getMessage());
}
}
}

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class StudentCSVGenerator {

public static void main(String[] args) {


List<Student> students = new ArrayList<>();
students.add(new Student(1, "Alice", 90));
students.add(new Student(2, "Bob", 85));
students.add(new Student(3, "Charlie", 95));
students.add(new Student(4, "David", 78));
students.add(new Student(5, "Eve", 88));

String filename = "students.csv";

try (BufferedWriter writer = new BufferedWriter(new FileWriter(filename))) {


writer.write("StudentID,Name,Grade\n");
for (Student student : students) {
writer.write(student.getStudentID() + "," + student.getName() + "," +
student.getGrade() + "\n");
}
System.out.println("Student data written to " + filename);
} catch (IOException e) {
System.err.println("Error writing to file: " + e.getMessage());
}
}

static class Student {


private int studentID;
private String name;
private int grade;

public Student(int studentID, String name, int grade) {


this.studentID = studentID;
this.name = name;
this.grade = grade;
}

public int getStudentID() {


return studentID;
}

public String getName() {


return name;
}

public int getGrade() {


return grade;
}
}
}

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.

Counts Empty Lines: line.trim().isEmpty() identifies empty/whitespace-only lines.

Counts Words: line.trim().split("\\s+") splits by all whitespace characters.

Error Handling:

NullPointerException handled explicitly if filename is null.

IOException for file read problems.

Prints user-friendly error messages instead of crashing.

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.

Enhanced word counting with split("\\s+") to account for multiple spaces.

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:

BufferedWriter used with a buffer size of 8192 bytes.

Robust Error Handling:

Catches IOException, IllegalArgumentException, and general Exception.

Gives clear and non-crashing error messages.

Progress Indication:

Prints progress at 10% intervals using:

java
Copy code
if (i % (numLines / 10) == 0)
Custom Line Content:

Reads custom line format from second command-line argument.

Defaults to Line %d if not provided.

File Existence Check:

Uses Files.exists() to detect existing file.

Asks user for overwrite confirmation via Scanner.

Changes Made:
Added default line formatting with %d.

Added user prompt for overwriting file.

Added exception for invalid line count input.


Problem 3: StudentCSVGenerator.java
Objective:
Generate a CSV file containing student data.

Problems Solved:
Write CSV File:

Writes header row (StudentID,Name,Grade).

Writes each student's details.

Buffered Writing:

Uses BufferedWriter for performance.

Basic OOP Usage:

Uses an inner Student class with getters and constructor.

Changes Made:
Structured the Student class as static and self-contained.

Wrapped file writing in a try-with-resources block.

Ensured line formatting was correct (comma-separated values).

Summary of Key Improvements Across All Programs:


Feature Problem 1 Problem 2 Problem 3
Efficient I/O BufferedReader BufferedWriter BufferedWriter
Error Handling Yes Yes Yes
User Input via Args File name Line count & content No (uses static data)
Progress Indicator No Yes No
CSV Format No No Yes
Custom Data Support No Yes Can be added
Safe Overwrite CheckNo Yes Can be added

Would you like any enhancements next? For example:

Reading students from input

Sorting students before writing

Unit tests for these programs


Let me know!

You might also like