Java DataOutputStream Class
Data output stream lets an application write primitive Java data types to an output stream in a machine-independent way.
The following constructor is used to create a data output stream object.
DataOutputStream out = new DataOutputStream(OutputStream out);
Once the object is created successfully, you can refer to the methods given in the following list to write or otherwise operate on the stream.
| No. | Method Description |
|---|---|
| 1 |
public final void write(byte[] w, int off, int len)throws IOException Writes bytes from the specified byte array offstarting at offsetlento this byte array output stream. |
| 2 |
Public final int write(byte [] b)throws IOException Writes the specified byte to this byte array output stream. |
| 3 |
|
| 4 |
Public void flush()throws IOException Flushes this output stream and forces any buffered output bytes to be written out. |
| 5 |
public final void writeBytes(String s) throws IOException Writes the string to the underlying output stream as a sequence of bytes, with each character written in order and its high eight bits discarded. |
Example
The following example demonstrates the use of DataInputStream and DataOutputStream. It reads five lines from the text file test.txt, converts them to uppercase letters, and finally saves them to another file, test1.txt.
The contents of the test.tx file are as follows:
example1 example2 example3 example4 example5
Example
import java.io.*;
public class Test{
public static void main(String args[])throws IOException{
DataInputStream in = new DataInputStream(new FileInputStream("test.txt"));
DataOutputStream out = new DataOutputStream(new FileOutputStream("test1.txt"));
BufferedReader d = new BufferedReader(new InputStreamReader(in));
String count;
while((count = d.readLine()) != null){
String u = count.toUpperCase();
System.out.println(u);
out.writeBytes(u + " ,");
}
d.close();
out.close();
}
}
The result of compiling and running the above example is as follows:
EXAMPLE1 EXAMPLE2 EXAMPLE3 EXAMPLE4 EXAMPLE5
Other Extensions
Java Stream