Java Reference
In-Depth Information
Display 10.13
Writing to a Binary File (part 2 of 2)
8
try
9
{
10
ObjectOutputStream outputStream =
11
new ObjectOutputStream( new FileOutputStream("numbers.dat"));
12
int i;
13
for (i = 0; i < 5; i++)
14
outputStream.writeInt(i);
15
System.out.println("Numbers written to the file numbers.dat.");
16
outputStream.close();
17
}
18
catch (IOException e)
19
{
20
System.out.println("Problem with file output.");
21
}
22
}
23
}
F ILE R EPRESENTATION (after program is run)
0
1
2
3
4
This is a binary file. It really contains representations
of each number as bytes, that is, zeros and ones, and
is read as bytes. You cannot read this file with your
text editor.
Display 10.14 Some Methods in the Class ObjectOutputStream (part 1 of 2)
ObjectOutputStream and FileOutputStream are in the java.io package.
public ObjectOutputStream(OutputStream streamObject)
There is no constructor that takes a file name as an argument. If you want to create a stream using a
file name, you use
new ObjectOutputStream( new FileOutputStream( File_Name ))
This creates a blank file. If there already is a file named File_Name , then the old contents of the file
are lost.
If you want to create a stream using an object of the class File , you use
new ObjectOutputStream( new FileOutputStream( File_Object ))
The constructor for FileOutputStream may throw a FileNotFoundException , which is a kind of
IOException . If the FileOutputStream constructor succeeds, then the constructor for
ObjectOutputStream may throw a different IOException .
 
Search WWH ::




Custom Search