File output
import java.io.*;
import java.io.*; Step 1: Import the required packages:
import java.util.*r; Step 1.1: Import `java.io.*` for file handling.
Step 1.2: Import `java.util.Scanner` for user
public class StudentFileWriter { input
public static void main(String[] args) { Step 2: Declare the class
Scanner scanner = new `StudentFileWriter`.
Scanner(System.in); Step 3: Declare the `main` function.
Step 4: Create a `Scanner` object to read
try { input from the user.
"Student.txt" for writing Step 5: Use a `try` block to handle potential
FileWriter writer = new exceptions.
FileWriter("Student.txt"); Step 5.1: Create a `FileWriter` object to
write to the file `"Student.txt"`.
Step 6: Prompt the user for student details.
System.out.print("Enter the Step 6.1: Prompt and read the student's
student's name: "); name.
String name = scanner.nextLine(); Step 6.2: Prompt and read the roll number.
Step 6.3: Prompt and read the marks.
System.out.print("Enter the roll Step 7: Write the student details to the file
number: "); using the `FileWriter` object.
String rollNo = scanner.nextLine(); Step 7.1: Write the student's name in the
format `Name: <name>`.
System.out.print("Enter the marks: Step 7.2: Write the roll number in the format
"); `Roll Number: <roll number>`.
String marks = scanner.nextLine(); Step 7.3: Write the marks in the format
`Marks: <marks>`.
Step 8: Close the `FileWriter` to release file
writer.write("Name: " + name + "\n"); resources.
writer.write("Roll Number: " + rollNo Step 8.1: Display a message indicating that
+ "\n"); data has been successfully written to the
writer.write("Marks: " + marks + file.
"\n"); Step 9: Use a `catch` block to handle
`IOException`.
Step 9.1: If an error occurs, display `"An
writer.close(); error occurred while writing to the file."`.
System.out.println("Data has been Step 10: Use a `finally` block to close the
written to 'Student.txt'."); `Scanner` object.
Step 11: End the program.
} catch (IOException e) {
System.out.println("An error
occurred while writing to the file.");
e.printStackTrace();
} finally {
scanner.close();
}
}
}