Program 23: File Output
File output
import [Link].*;
import [Link].*r;
public class StudentFileWriter {
public static void main(String[] args) {
Scanner scanner = new
Scanner([Link]);
try {
"[Link]" for writing
FileWriter writer = new
FileWriter("[Link]");
[Link]("Enter the
student's name: ");
String name = [Link]();
[Link]("Enter the roll
number: ");
String rollNo = [Link]();
[Link]("Enter the marks:
");
String marks = [Link]();
[Link]("Name: " + name + "
");
[Link]("Roll Number: " + rollNo
+ "
");
[Link]("Marks: " + marks +
"
");
[Link]();
[Link]("Data has been
written to '[Link]'.");
} catch (IOException e) {
[Link]("An error
occurred while writing to the file.");
[Link]();
} finally {
[Link]();
}
}
Algorithm:
Step 1: Import the required packages:
Step 1.1: Import `[Link].*` for file handling.
Step 1.2: Import `[Link]` 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 `"[Link]"`.
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.