Java DataOutputStream Class
The DataOutputStream class allows applications to write Java primitive data types to an output stream in a machine-independent manner.
The following constructor is used to create a DataOutputStream object.
DataOutputStream out = new DataOutputStream(OutputStream out);
Once the object is successfully created, you can use the methods listed below to write to the stream or perform other operations.
No. | Method Description |
---|---|
1 | public final void write(byte[] w, int off, int len) throws IOException <br> Writes len bytes from the specified byte array starting at offset off to this byte array output stream. |
2 | public final int write(byte[] b) throws IOException <br> Writes the specified byte to this byte array output stream. |
3 | public final void writeBoolean() throws IOException, <br> public final void writeByte() throws IOException, <br> public final void writeShort() throws IOException, <br> public final void writeInt() throws IOException <br> These methods write the specified primitive data types to the output stream as bytes. |
4 | public void flush() throws IOException <br> Flushes this output stream and forces any buffered output bytes to be written out. |
5 | public final void writeBytes(String s) throws IOException <br> Writes the string to the underlying output stream as a sequence of bytes, with each character written sequentially, discarding its high eight bits. |
Example
The following example demonstrates the use of DataInputStream and DataOutputStream. It reads 5 lines from the text file test.txt
, converts them to uppercase, and saves them in another file test1.txt
.
Contents of test.txt
:
tutorialpro1
tutorialpro2
tutorialpro3
tutorialpro4
tutorialpro5
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 above example compiles and runs with the following output:
tutorialpro1
tutorialpro2
tutorialpro3
tutorialpro4
tutorialpro5