0% found this document useful (0 votes)
0 views1 page

PROGRAM 22 Binary 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)
0 views1 page

PROGRAM 22 Binary 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/ 1

Binary output

import java.io.*; Step 1: Import the required packages:


import java.util.Scanner; Step 1.1: Import `java.io.*` for file handling.
Step 1.2: Import `java.util.Scanner` for user
public class StudentBinaryFile { input.
public static void main() { Step 2: Declare the class
Scanner scanner = new `StudentBinaryFile`.
Scanner(System.in); Step 3: Declare the `main` function.
Step 4: Create a `Scanner` object to read
try { input from the user.
Step 5: Use a `try` block to handle potential
FileOutputStream fileOut = new exceptions.
FileOutputStream("Student.dat"); Step 5.1: Create a `FileOutputStream`
DataOutputStream dataOut = new object to write to the file `"Student.dat"`.
DataOutputStream(fileOut); Step 5.2: Wrap the `FileOutputStream`
object with a `DataOutputStream` to handle
binary data.
System.out.print("Enter the
student's name: "); Step 6: Prompt the user for student details.
String name = scanner.nextLine(); Step 6.1: Prompt and read the student's
name as a string.
System.out.print("Enter the roll Step 6.2: Prompt and read the roll number
number: "); as an integer.
int rollNo = scanner.nextInt(); Step 6.3: Prompt and read the marks as a
double.
System.out.print("Enter the marks: Step 7: Write the student details to the file
"); in binary format using the
double marks = `DataOutputStream` object.
scanner.nextDouble(); Step 7.1: Write the student's name using
`writeUTF()`.
Step 7.2: Write the roll number using
dataOut.writeUTF(name); `writeInt()`.
dataOut.writeInt(rollNo); Step 7.3: Write the marks using
dataOut.writeDouble(marks); `writeDouble()`.
Step 8: Close the `DataOutputStream` and
`FileOutputStream` to release file
dataOut.close(); resources.
fileOut.close(); Step 8.1: Display a message indicating that
data has been successfully written to the
System.out.println("Data has been file.
written to 'Student.dat' in binary format."); Step 9: Use a `catch` block to handle
`IOException`.
} catch (IOException e) { Step 9.1: If an error occurs, display `"An
System.out.println("An error error occurred while writing to the file."`.
occurred while writing to the file."); Step 10: Use a `finally` block to close the
e.printStackTrace(); `Scanner` object.
} finally { Step 11: End the program.
scanner.close();
}
}
}

You might also like