public class BinaryOutputDemo
1: //BinaryOutputDemo.java
2:
3: import java.io.File;
4: import java.io.FileOutputStream;
5: import java.io.ObjectOutputStream;
6: import java.io.FileNotFoundException;
7: import java.io.IOException;
8: import java.util.Scanner;
9:
10: public class BinaryOutputDemo
11: {
12: public static void main(String[] args)
13: {
14: String fileName = "numbers.dat";
15: try
16: {
17: ObjectOutputStream outputStream =
18: new ObjectOutputStream(new FileOutputStream(fileName));
19: Scanner keyboard = new Scanner(System.in);
20: System.out.println("\nEnter some nonnegative integers, "
21: + "followed\nby a single negative integer at the end:");
22: int anInteger;
23: do
24: {
25: anInteger = keyboard.nextInt();
26: outputStream.writeInt(anInteger);
27: }
28: while (anInteger >= 0);
29: System.out.println("All integers, plus the sentinel value, "
30: + "\nhave been written to the file " + fileName + ".");
31: outputStream.close();
32: }
33: catch(FileNotFoundException e)
34: {
35: System.out.println("Error opening the file " + fileName + ".");
36: }
37: catch(IOException e)
38: {
39: System.out.println("Problem with output to file " + fileName + ".");
40: }
41: }
42: }
43: