0% found this document useful (0 votes)
3 views

problem 1-

The document contains three Java programming problems focused on file handling. Problem 1 involves counting lines, empty lines, and words in a text file while handling errors gracefully. Problem 2 requires writing a large number of lines to a file with efficient buffering and error handling, and Problem 3 generates a CSV file with student data.

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)
3 views

problem 1-

The document contains three Java programming problems focused on file handling. Problem 1 involves counting lines, empty lines, and words in a text file while handling errors gracefully. Problem 2 requires writing a large number of lines to a file with efficient buffering and error handling, and Problem 3 generates a CSV file with student data.

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/ 6

problem 1:

Problem:

Write a Java program that reads a text file and performs the following tasks:

1. Counts Lines: Counts the total number of lines in the file.

2. Counts Empty Lines: Counts the number of lines that are empty (contain only whitespace or
are completely blank).

3. Counts Words: Counts the total number of words in the file (splitting the lines by whitespace).

4. Handles Errors Gracefully: Provides informative error messages if the file is not found or if
there are any I/O errors. The program should not terminate abruptly. It should handle
NullPointerException if the filename is null or invalid.

5. Efficient Processing: Processes the file in a memory-efficient way, suitable for even relatively
large files. The whole file should not be loaded into memory at once.

Sample Text File (input.txt):

This is the first line.


This is the second line.

This is the third line. It has some extra spaces.

This is the fourth line.

Improved Java Code (EnhancedLineCounter.java):

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>");
System.exit(1);
}

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: Invalid filename provided.");
System.exit(1);
} catch (IOException e) {
System.err.println("Error reading file: " + e.getMessage());
System.exit(1);
}

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


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

Compilation and Execution:

1. Save the code as EnhancedLineCounter.java.

2. Save the sample text as input.txt.

3. Compile: javac EnhancedLineCounter.java

4. Run: java EnhancedLineCounter input.txt

Expected Output:

Total lines: 4
Empty lines: 1
Total words: 20
Problem 2:

Write a Java program that writes a large number of lines to a file using a BufferedWriter, but
with these improvements:

1. Efficient Buffering: Optimize the BufferedWriter to write data efficiently, minimizing disk I/O
operations, especially when writing a very large number of lines.

2. Robust Error Handling: Implement comprehensive error handling to catch and report various
exceptions that might occur during file writing, such as IOException, NullPointerException, and
IllegalArgumentException. The program should not crash but instead give informative error
messages.

3. Progress Indication: Add a mechanism to display the progress of the file writing (e.g.,
percentage complete) to the user, providing feedback during long operations.

4. Customizable Line Content: Allow the user to specify the content of each line via a command-
line argument. If no argument is provided, use a default line content.

5. File Existence Check: Check if the output file already exists. If it does, either prompt the user
for confirmation to overwrite or choose an alternative filename to prevent accidental data loss.

Improved Java Code (EfficientBufferedWriter.java):

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 line content
//Process command line arguments
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("Error: 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;
}
scanner.close();
}

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


buffer size
for (int i = 0; i < numLines; i++) {
writer.write(String.format(lineContent, i));
if (i % (numLines / 10) == 0) { //Progress indicator
System.out.println(String.format("%.1f%% complete", (double) i / numLines * 100));
}
}
} catch (IOException e) {
System.err.println("Error writing to file: " + e.getMessage());
} catch (IllegalArgumentException e){
System.err.println("Error: "+ e.getMessage());
} catch (Exception e){
System.err.println("An unexpected error occurred: " + e.getMessage());
}
}
}
Compilation and Execution:

1. Save the code as EfficientBufferedWriter.java.

2. Compile: javac EfficientBufferedWriter.java

3. Run (example to write 50000 lines with custom content): java EfficientBufferedWriter 50000
"My custom line"

The output will show progress updates as the file is written, and the output.txt file will be created
(or overwritten if it already exists and the user confirms).

problem 3:
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))) {


// Write the header row
writer.write("StudentID,Name,Grade\n");

// Write the student data rows


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

This code will create a file named students.csv with the following content:

StudentID,Name,Grade
1,Alice,90
2,Bob,85
3,Charlie,95
4,David,78
5,Eve,88

You might also like