📅  最后修改于: 2023-12-03 14:42:14.612000             🧑  作者: Mango
The DataOutputStream
class in Java IO provides an efficient and convenient way to write primitive data types to an output stream. It works in conjunction with the DataInputStream
class to read the same data types from an input stream.
To use DataOutputStream
in your Java program, follow these steps:
First, you need to create an output stream using any of the available implementations, such as FileOutputStream
, ByteArrayOutputStream
, or Socket.getOutputStream()
. For example:
OutputStream outputStream = new FileOutputStream("output.txt");
Next, create a DataOutputStream
object by passing the output stream as a parameter to its constructor. For example:
DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
Now, you can use various write
methods provided by DataOutputStream
to write data to the output stream. For example, to write a string and an integer:
dataOutputStream.writeUTF("Hello, World!");
dataOutputStream.writeInt(42);
After writing the data, it is important to close the stream to release any system resources associated with it. The DataOutputStream
class automatically closes the underlying output stream when it is closed. For example:
dataOutputStream.close();
Here's a complete example that demonstrates writing primitive data types to a file using DataOutputStream
:
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class DataOutputStreamExample {
public static void main(String[] args) {
try {
OutputStream outputStream = new FileOutputStream("output.txt");
DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
dataOutputStream.writeInt(42);
dataOutputStream.writeDouble(3.14);
dataOutputStream.writeUTF("Hello, World!");
dataOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
This creates a file named "output.txt" with the values 42
, 3.14
, and "Hello, World!"
written to it.
DataOutputStream
in Java IO provides a convenient way to write primitive data types and strings to an output stream. It is particularly useful when dealing with binary formats or when sending data over a network. The provided example should help you get started with writing data using DataOutputStream
.