0% found this document useful (0 votes)
1 views4 pages

Program 10 File Output

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

Program 10 File Output

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

Program 21: File Input

File input

import java.io.*;

import java.util.*;

public class StudentMarks {

public static void main() {

String fileName = "student_marks.txt";

try {

FileReader fr = new

FileReader(fileName);

BufferedReader br = new

BufferedReader(fr);

System.out.println("Roll

NoNameMarks");

String line;

while ((line = br.readLine()) != null) {


String[] parts = line.split(",");

if (parts.length == 3) {

String rollNo = parts[0].trim();

String name = parts[1].trim();

String marks = parts[2].trim();

System.out.printf("%s%s%s

", rollNo,

name, marks);

} else {

System.out.println("Invalid data

format: " + line);

br.close();

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();

Algorithm: Display Student Marks from a

File

Step 1: Import the java.io package to

handle file reading and exceptions.

Step 2: Declare the class StudentMarks.

Step 3: Declare the main function.

Step 4: Specify the file name as

"student_marks.txt".

Step 5: Use a try block to handle potential

file-related exceptions.

Step 5.1: Create a FileReader object to

open the file.

Step 5.2: Wrap the FileReader with a

BufferedReader to read the file line by line.

Step 6: Print the table header "Roll

NoNameMarks".

Step 7: Read and process each line of the

file using a while loop.

Step 7.1: Use BufferedReader.readLine() to

read the current line.

Step 7.2: Split the line into parts using a


comma (,) as the delimiter.

Step 7.3: Check if the line contains exactly

three parts.

Step 7.3.1: If valid:

Step 7.3.1.1: Extract Roll No, Name, and

Marks.

Step 7.3.1.2: Print the values in tabular

format using System.out.printf.

Step 7.3.2: If invalid:

Step 7.3.2.1: Print an error message

indicating invalid data.

Step 8: Close the BufferedReader and

FileReader to release file resources.

Step 9: Use a catch block to handle

exceptions.

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.".

Step 10: End the program.

You might also like