DataOutputStream Class
Package: java.io
The DataOutputStream
class is the main class you’ll work with for writing data to binary files. This class builds on the BufferedOutputStream
class by adding the ability to write primitive data types. The BufferedOutputStream
class builds on the FileOutputStream
class by adding buffered output for the sake of efficiency. And the FileOutputStream
class provides the basic capabilities of writing characters to an output stream.
Constructor
Constructor |
Description |
|
Creates a data output stream for the specified output stream. |
Methods
Method |
Description |
|
Closes the file. |
|
Writes the contents of the buffer to the hard drive. |
|
Returns the number of bytes written to the file. |
|
Writes a |
|
Writes a |
|
Writes a |
|
Writes a |
|
Writes a |
|
Writes an |
|
Writes a |
|
|
|
Writes a string stored in UTF format to the output stream. It throws |
Creating a DataOutputStream
To create a DataOutputStream
object, you typically must also create a BufferedOutputStream
object, a FileOut putStream
object, and a File
object. Here is a typical sequence:
File file;
FileOutputStream fstream;
BufferedOutputStream bstream;
DataOutputStream out;
file = new File(“myfile.bin”);
fstream = new FileOutputStream(file);
bstream = new BufferedOutputStream(fos);
out = new DataOutputStream(bos);
Note that the FileOutputStream
class has an optional boolean
parameter that you can use to indicate that the file should be appended, if it exists. To use this feature, call the FileOutputStream
constructor like this:
fstream = new FileOutputStream(file, true);
Writing to a binary stream
After you successfully connect a DataOutputStream
to a file, you can call the various write
methods to write different data types to the file. The following code writes a string value followed by an integer and a double:
out.writeUTF(“This is a string”);
out.writeInt(42);
out.writeDouble(99.997);
These methods throw IOException
. As a result, you should enclose them in a try/catch
block. (For more information, see try Statement in Part 2.)
out.flush();
Also, when you finish writing data to the file, close the file by calling the close
method, like this:
out.close();
The flush
and close
methods also throw IOException
, so you need a try/catch
block to catch the exception.