Docsity

COMPUTER PROGRAMMING, Lecture notes of Computer Programming

Toggle sidebar
bg1
File I/O (Input and Output
File I/O (Input and Output) is essential for handling files in Java.
Here’s a structured laboratory exercise to practice reading and writing files.
Objective:
Learn how to use Java's FileReader, FileWriter, BufferedReader, and BufferedWriter classes
for file input and output operations.
Tasks:
1. Writing to a File (Basic File Output)
Create a program that writes a simple message to a text file.
import java.io.FileWriter;
import java.io.IOException;
public class FileWriteExample {
public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("output.txt");
writer.write("Hello, this is a file writing example in Java!");
writer.close();
System.out.println("File written successfully.");
} catch (IOException e) {
System.out.println("Error writing to file: " + e.getMessage());
}
}
}
2. Reading from a File (Basic File Input)
Write a program to read data from a file.
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
public class FileReadExample {
public static void main(String[] args) {
try {
BufferedReader reader = new BufferedReader(new FileReader("output.txt"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (IOException e) {
System.out.println("Error reading from file: " + e.getMessage());
}
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe

Partial preview of the text

Download COMPUTER PROGRAMMING and more Lecture notes Computer Programming in PDF only on Docsity!

File I/O (Input and Output) is essential for handling files in Java.

Here’s a structured laboratory exercise to practice reading and writing files.

Objective:

Learn how to use Java's FileReader, FileWriter, BufferedReader, and BufferedWriter classes

for file input and output operations.

Tasks:

1. Writing to a File (Basic File Output)

Create a program that writes a simple message to a text file.

import java.io.FileWriter; import java.io.IOException; public class FileWriteExample { public static void main(String[] args) { try { FileWriter writer = new FileWriter("output.txt"); writer.write("Hello, this is a file writing example in Java!"); writer.close(); System.out.println("File written successfully."); } catch (IOException e) { System.out.println("Error writing to file: " + e.getMessage()); } } }

2. Reading from a File (Basic File Input)

Write a program to read data from a file.

import java.io.FileReader; import java.io.BufferedReader; import java.io.IOException; public class FileReadExample { public static void main(String[] args) { try { BufferedReader reader = new BufferedReader(new FileReader("output.txt")); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } reader.close(); } catch (IOException e) { System.out.println("Error reading from file: " + e.getMessage()); }

3. Writing Multiple Lines to a File

Use BufferedWriter to write multiple lines.

import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; public class MultiLineFileWrite { public static void main(String[] args) { try { BufferedWriter writer = new BufferedWriter(new FileWriter("multi_output.txt")); writer.write("Line 1: Java File Handling"); writer.newLine(); writer.write("Line 2: Writing multiple lines."); writer.newLine(); writer.close(); System.out.println("File written successfully."); } catch (IOException e) { System.out.println("Error writing to file: " + e.getMessage()); } } }

4. Checking if a File Exists

Create a program to check whether a file exists.

import java.io.File; public class FileCheckExample { public static void main(String[] args) { File file = new File("output.txt"); if (file.exists()) { System.out.println("File exists."); } else { System.out.println("File does not exist."); } } }

An application program using file input and output allows for persistent data storage. Here’s an example: a simple Student Management System that reads and writes student records to a file. Objective: Create a Java application that:

  1. Writes student records (name, age, and grade) to a file.
  2. Reads student records from a file.
  3. Appends new student records without overwriting existing data.

Implementation:

  1. Writing Student Records to a File This program collects student details and writes them to a file. import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class StudentFileWriter { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter Student Name: "); String name = scanner.nextLine(); System.out.print("Enter Student Age: "); int age = scanner.nextInt(); scanner.nextLine(); // Consume newline System.out.print("Enter Student Grade: "); String grade = scanner.nextLine(); try { FileWriter writer = new FileWriter("students.txt", true); // Append mode writer.write(name + "," + age + "," + grade + "\n"); writer.close(); System.out.println("Student record saved successfully."); } catch (IOException e) { System.out.println("Error writing to file: " + e.getMessage()); } scanner.close(); } }
  1. Reading Student Records from a File This program reads and displays student records from the file. import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class StudentFileReader { public static void main(String[] args) { try { BufferedReader reader = new BufferedReader(new FileReader("students.txt")); String line; System.out.println("Student Records:"); while ((line = reader.readLine()) != null) { String[] data = line.split(","); System.out.println("Name: " + data[0] + ", Age: " + data[1] + ", Grade: " + data[2]); } reader.close(); } catch (IOException e) { System.out.println("Error reading from file: " + e.getMessage()); } } } Here's a Java program that searches for a student record based on a given name from a file. How It Works:
    1. Reads the file (students.txt) that contains records in the format: John,20,A Alice,22,B Mark,21,A
    2. Searches for the student name entered by the user.
    3. Displays the student's details if found; otherwise, informs the user that no record exists. Java Implementation: import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.Scanner; public class StudentSearch { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter student name to search: "); String searchName = scanner.nextLine().trim(); boolean found = false; try { BufferedReader reader = new BufferedReader(new FileReader("students.txt")); String line; while ((line = reader.readLine()) != null) { String[] data = line.split(",");

Updating a student record in a file involves reading the file, modifying the necessary data, and writing it back. Here’s a Java program to achieve this: How It Works:

  1. Reads the file (students.txt) containing records in "Name,Age,Grade" format.
  2. Searches for a specific student by name.
  3. If found, prompts the user for new data and updates the record.
  4. Writes the modified data back to the file. import java.io.; import java.util.; public class StudentUpdate { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); List studentRecords = new ArrayList<>(); boolean updated = false; System.out.print("Enter student name to update: "); String searchName = scanner.nextLine().trim(); try { BufferedReader reader = new BufferedReader(new FileReader("students.txt")); String line; while ((line = reader.readLine()) != null) { String[] data = line.split(","); if (data[0].equalsIgnoreCase(searchName)) { // Case-insensitive match System.out.println("Current Record: " + line); // Getting updated details System.out.print("Enter new age: "); String newAge = scanner.nextLine(); System.out.print("Enter new grade: "); String newGrade = scanner.nextLine(); line = data[0] + "," + newAge + "," + newGrade; // Update record updated = true; } studentRecords.add(line); // Store records } reader.close(); // Rewrite file if update occurred if (updated) { BufferedWriter writer = new BufferedWriter(new FileWriter("students.txt")); for (String record : studentRecords) { writer.write(record); writer.newLine(); } writer.close(); System.out.println("Student record updated successfully."); } else { System.out.println("Student record not found.");

} catch (IOException e) { System.out.println("Error processing the file: " + e.getMessage()); } scanner.close(); } } How to Use:

  1. Ensure students.txt exists with records formatted as "Name,Age,Grade" (e.g., John,20,A).
  2. Run the program and enter the student's name to update.
  3. If found, enter the new age and grade.
  4. The file will be rewritten with the updated record.

A menu-driven program using file I/O allows users to interact with stored data through different options. Here’s how we can structure a Student Management System with a menu, enabling users to add, view, search, update, and delete student records. How It Works:

  1. The program displays a menu for the user to select an action.
  2. Based on user choice, it: o Writes new student records to a file. o Reads and displays all records. o Searches for a specific student. o Updates an existing student record. o Deletes a student record. Java Implementation: import java.io.; import java.util.; public class StudentMenuSystem { static final String FILE_NAME = "students.txt"; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while (true) { System.out.println("\nStudent Management System"); System.out.println("1. Add Student"); System.out.println("2. View Students"); System.out.println("3. Search Student"); System.out.println("4. Update Student"); System.out.println("5. Delete Student"); System.out.println("6. Exit"); System.out.print("Choose an option: "); int choice = scanner.nextInt(); scanner.nextLine(); // Consume newline switch (choice) { case 1: addStudent(scanner); break; case 2: viewStudents(); break; case 3: searchStudent(scanner); break; case 4: updateStudent(scanner); break; case 5: deleteStudent(scanner); break; case 6: System.out.println("Exiting...");

found = true; break; } } if (!found) { System.out.println("Student record not found."); } } catch (IOException e) { System.out.println("Error reading file: " + e.getMessage()); } } // Update a student record static void updateStudent(Scanner scanner) { System.out.print("Enter student name to update: "); String searchName = scanner.nextLine().trim(); List studentRecords = new ArrayList<>(); boolean updated = false; try (BufferedReader reader = new BufferedReader(new FileReader(FILE_NAME))) { String line; while ((line = reader.readLine()) != null) { String[] data = line.split(","); if (data[0].equalsIgnoreCase(searchName)) { System.out.print("Enter new age: "); String newAge = scanner.nextLine(); System.out.print("Enter new grade: "); String newGrade = scanner.nextLine(); line = data[0] + "," + newAge + "," + newGrade; updated = true; } studentRecords.add(line); } } catch (IOException e) { System.out.println("Error processing the file: " + e.getMessage()); } if (updated) { try (BufferedWriter writer = new BufferedWriter(new FileWriter(FILE_NAME))) { for (String record : studentRecords) { writer.write(record); writer.newLine(); } System.out.println("Student record updated successfully."); } catch (IOException e) { System.out.println("Error writing file: " + e.getMessage()); } } else { System.out.println("Student record not found."); } } // Delete a student record

static void deleteStudent(Scanner scanner) { System.out.print("Enter student name to delete: "); String searchName = scanner.nextLine().trim(); List studentRecords = new ArrayList<>(); boolean deleted = false; try (BufferedReader reader = new BufferedReader(new FileReader(FILE_NAME))) { String line; while ((line = reader.readLine()) != null) { String[] data = line.split(","); if (data[0].equalsIgnoreCase(searchName)) { deleted = true; continue; } studentRecords.add(line); } } catch (IOException e) { System.out.println("Error processing the file: " + e.getMessage()); } if (deleted) { try (BufferedWriter writer = new BufferedWriter(new FileWriter(FILE_NAME))) { for (String record : studentRecords) { writer.write(record); writer.newLine(); } System.out.println("Student record deleted successfully."); } catch (IOException e) { System.out.println("Error writing file: " + e.getMessage()); } } else { System.out.println("Student record not found."); } } }