File input
import java.io.*;
import java.util.*; Algorithm: Display Student Marks from a
File
public class StudentMarks { Step 1: Import the java.io package to
public static void main() { handle file reading and exceptions.
String fileName = "student_marks.txt"; Step 2: Declare the class StudentMarks.
try { Step 3: Declare the main function.
Step 4: Specify the file name as
FileReader fr = new "student_marks.txt".
FileReader(fileName); Step 5: Use a try block to handle potential
BufferedReader br = new file-related exceptions.
BufferedReader(fr); Step 5.1: Create a FileReader object to
open the file.
Step 5.2: Wrap the FileReader with a
System.out.println("Roll BufferedReader to read the file line by line.
No\tName\t\tMarks"); Step 6: Print the table header "Roll
No\tName\t\tMarks".
Step 7: Read and process each line of the
String line; file using a while loop.
Step 7.1: Use BufferedReader.readLine() to
read the current line.
while ((line = br.readLine()) != null) { Step 7.2: Split the line into parts using a
comma (,) as the delimiter.
String[] parts = line.split(","); Step 7.3: Check if the line contains exactly
three parts.
if (parts.length == 3) { Step 7.3.1: If valid:
Step 7.3.1.1: Extract Roll No, Name, and
String rollNo = parts[0].trim(); Marks.
String name = parts[1].trim(); Step 7.3.1.2: Print the values in tabular
String marks = parts[2].trim(); format using System.out.printf.
Step 7.3.2: If invalid:
Step 7.3.2.1: Print an error message
indicating invalid data.
System.out.printf("%s\t%s\t%s\n", rollNo, Step 8: Close the BufferedReader and
name, marks); FileReader to release file resources.
} else { Step 9: Use a catch block to handle
System.out.println("Invalid data exceptions.
format: " + line); Step 9.1: If the file is not found, print "File
} not found: student_marks.txt".
} Step 9.2: If there is an I/O error, print "An
error occurred while reading the file.".
br.close(); Step 10: End the program.
fr.close();
} catch (FileNotFoundException e) {
System.out.println("File not found: "
+ fileName);
} catch (IOException e) {
System.out.println("An error
occurred while reading the file.");
e.printStackTrace();
}
}
}