Program 22: Binary Output
Code:
import java.io.*;
import java.util.Scanner;
public class StudentBinaryFile {
public static void main() {
Scanner scanner = new Scanner(System.in);
try {
FileOutputStream fileOut = new FileOutputStream("Student.dat");
DataOutputStream dataOut = new DataOutputStream(fileOut);
System.out.print("Enter the student's name: ");
String name = scanner.nextLine();
System.out.print("Enter the roll number: ");
int rollNo = scanner.nextInt();
System.out.print("Enter the marks: ");
double marks = scanner.nextDouble();
dataOut.writeUTF(name);
dataOut.writeInt(rollNo);
dataOut.writeDouble(marks);
dataOut.close();
fileOut.close();
System.out.println("Data has been written to 'Student.dat' in binary format.");
} 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 `StudentBinaryFile`.
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 `FileOutputStream` object to write to the file `"Student.dat"`.
Step 5.2: Wrap the `FileOutputStream` object with a `DataOutputStream` to handle binary data.
Step 6: Prompt the user for student details.
Step 6.1: Prompt and read the student's name as a string.
Step 6.2: Prompt and read the roll number as an integer.
Step 6.3: Prompt and read the marks as a double.
Step 7: Write the student details to the file in binary format using the `DataOutputStream` object.
Step 7.1: Write the student's name using `writeUTF()`.
Step 7.2: Write the roll number using `writeInt()`.
Step 7.3: Write the marks using `writeDouble()`.
Step 8: Close the `DataOutputStream` and `FileOutputStream` 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.