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

Program 9 File Input

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)
2 views4 pages

Program 9 File Input

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 23: File Output

File output

import java.io.*;

import java.util.*r;

public class StudentFileWriter {

public static void main(String[] args) {

Scanner scanner = new

Scanner(System.in);

try {

"Student.txt" for writing

FileWriter writer = new

FileWriter("Student.txt");

System.out.print("Enter the

student's name: ");

String name = scanner.nextLine();

System.out.print("Enter the roll

number: ");

String rollNo = scanner.nextLine();


System.out.print("Enter the marks:

");

String marks = scanner.nextLine();

writer.write("Name: " + name + "

");

writer.write("Roll Number: " + rollNo

+ "

");

writer.write("Marks: " + marks +

"

");

writer.close();

System.out.println("Data has been

written to 'Student.txt'.");

} catch (IOException e) {

System.out.println("An error

occurred while writing to the file.");

e.printStackTrace();

} finally {

scanner.close();

}
}

Algorithm:

Step 1: Import the required packages:

Step 1.1: Import `java.io.*` for file handling.

Step 1.2: Import `java.util.Scanner` for user

input

Step 2: Declare the class

`StudentFileWriter`.

Step 3: Declare the `main` function.

Step 4: Create a `Scanner` object to read

input from the user.

Step 5: Use a `try` block to handle potential

exceptions.

Step 5.1: Create a `FileWriter` object to

write to the file `"Student.txt"`.

Step 6: Prompt the user for student details.

Step 6.1: Prompt and read the student's

name.

Step 6.2: Prompt and read the roll number.

Step 6.3: Prompt and read the marks.

Step 7: Write the student details to the file

using the `FileWriter` object.

Step 7.1: Write the student's name in the

format `Name: <name>`.

Step 7.2: Write the roll number in the format

`Roll Number: <roll number>`.


Step 7.3: Write the marks in the format

`Marks: <marks>`.

Step 8: Close the `FileWriter` to release file

resources.

Step 8.1: Display a message indicating that

data has been successfully written to the

file.

Step 9: Use a `catch` block to handle

`IOException`.

Step 9.1: If an error occurs, display `"An

error occurred while writing to the file."`.

Step 10: Use a `finally` block to close the

`Scanner` object.

Step 11: End the program.

You might also like