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