In this article, we'll dive into the particulars of DataOutputStream and understand its primary purpose: to write primitive Java data types to an output stream in a machine-independent way.
1. Overview
DataOutputStream is located in the java.io package, DataOutputStream wraps around an existing output stream and provides methods for writing data types like int, float, boolean, and more. It is often paired with DataInputStream for reading the data back.
2. Key Features
Machine Independence: Values written by DataOutputStream are guaranteed to be read back by DataInputStream in the exact same way, regardless of the platform.
Writes Strings in UTF Format: The class has a writeUTF() method which writes strings in a modified UTF-8 format.
3. Constructing a DataOutputStream
To create an instance, you typically wrap it around another output stream:
String filename = "datafile.dat";
try (DataOutputStream dos = new DataOutputStream(new FileOutputStream(filename))) {
4. Writing Data
Here are some methods provided by DataOutputStream:
writeBoolean(boolean v): Writes a boolean value.
writeInt(int v): Writes an integer value.
writeDouble(double v): Writes a double value.
writeUTF(String s): Writes a string in UTF format.
5. Example: Using DataOutputStream
Let's create a simple program that writes some data types using DataOutputStream.
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class DataOutputStreamExample {
public static void main(String[] args) {
String filename = "datafile.dat";
try (DataOutputStream dos = new DataOutputStream(new FileOutputStream(filename))) {
dos.writeInt(12345);
dos.writeDouble(98.6);
dos.writeBoolean(true);
dos.writeUTF("Hello, World!");
System.out.println("Data written to " + filename);
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
}
// Expected Output:
// Data written to datafile.dat
6. Considerations
Binary Data: The file created by DataOutputStream contains binary data, so you can't read it with a typical text editor.
Order Matters: When reading data back using DataInputStream, make sure to follow the exact order in which data items were written. For instance, if you write an integer followed by a double, you should read the integer first and then the double.
Related Java I/O Classes
- FileOutputStream Class in Java
- FileInputStream class in Java
- ByteArrayOutputStream Class in Java
- ByteArrayInputStream Class in Java
- DataOutStream Class in Java
- DataInputStream Class in Java
- ObjectOutputStream Class in Java
- ObjectInputStream Class in Java
- BufferedOutputStream Class in Java
- BufferedInputStream Class in Java
- BufferedWriter Class in Java
- BufferedReader Class in Java
- FileWriter Class in Java
- FileReader Class in Java
Comments
Post a Comment
Leave Comment