Java DataOutputStream Tutorial with Examples
1. DataOutputStream
No ADS
DataOutputStream is commonly used to write primitive data to another OutputStream. An application then can use the DataInputStream to read the data back.
public class DataOutputStream extends FilterOutputStream implements DataOutput
DataOutputStream is recommended for writing tabular data, like Excel. (See the example in the middle of this article).
OrderDate | Finished | Item | Units | UnitCost | Total |
2020-01-06 | Pencil | 95 | 1.99 | 189.05 | |
2020-01-23 | Binder | 50 | 19.99 | 999.50 | |
2020-02-09 | Pencil | 36 | 4.99 | 179.64 | |
2020-02-26 | Pen | 27 | 19.99 | 539.73 | |
2020-03-15 | Pencil | 56 | 2.99 | 167.44 |
- ByteArrayOutputStream
- FileOutputStream
- FilterOutputStream
- ObjectOutputStream
- PipedOutputStream
- BufferedOutputStream
- OutputStream
- PrintStream
- CheckedOutputStream
- CipherOutputStream
- DeflaterOutputStream
- DigestOutputStream
- InflaterOutputStream
3. Methods
public final void writeBoolean(boolean v) throws IOException
public final void writeByte(int v) throws IOException
public final void writeShort(int v) throws IOException
public final void writeChar(int v) throws IOException
public final void writeInt(int v) throws IOException
public final void writeLong(long v) throws IOException
public final void writeFloat(float v) throws IOException
public final void writeDouble(double v) throws IOException
public final void writeBytes(String s) throws IOException
public final void writeChars(String s) throws IOException
public final void writeUTF(String str) throws IOException
public final int size()
Other methods inherited from parent classes:
public static OutputStream nullOutputStream()
public void write(int b) throws IOException
public void write(byte b[]) throws IOException
public void write(byte b[], int off, int len) throws IOException
public void flush() throws IOException
public void close() throws IOException
4. Examples
No ADS
DataOutputStream is commonly used to write structured data like Excel. Now, we will write the following data table to a file:
OrderDate | Finished | Item | Units | UnitCost | Total |
2020-01-06 | Pencil | 95 | 1.99 | 189.05 | |
2020-01-23 | Binder | 50 | 19.99 | 999.50 | |
2020-02-09 | Pencil | 36 | 4.99 | 179.64 | |
2020-02-26 | Pen | 27 | 19.99 | 539.73 | |
2020-03-15 | Pencil | 56 | 2.99 | 167.44 |
First, write an Order class that simulates the single-row data of a table.
Order.java
package org.o7planning.dataoutputstream.ex;
import java.time.LocalDate;
public class Order {
private LocalDate orderDate;
private boolean finished;
private String item;
private int units;
private float unitCost;
private float total;
public Order(LocalDate orderDate, boolean finished, //
String item, int units, float unitCost, float total) {
this.orderDate = orderDate;
this.finished = finished;
this.item = item;
this.units = units;
this.unitCost = unitCost;
this.total = total;
}
public LocalDate getOrderDate() {
return orderDate;
}
public boolean isFinished() {
return finished;
}
public String getItem() {
return item;
}
public int getUnits() {
return units;
}
public float getUnitCost() {
return unitCost;
}
public float getTotal() {
return total;
}
}
Next, use DataOutputStream to write the above data table to a file:
WriteDataFile_example1.java
package org.o7planning.dataoutputstream.ex;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.time.LocalDate;
public class WriteDataFile_example1 {
// Windows: C:/somepath/data-file.txt
private static final String filePath = "/Volumes/Data/test/data-file.txt";
public static void main(String[] args) throws IOException {
Order[] orders = new Order[] { //
new Order(LocalDate.of(2020, 1, 6), true, "Pencil", 95, 1.99f, 189.05f),
new Order(LocalDate.of(2020, 1, 23), false, "Binder", 50, 19.99f, 999.50f),
new Order(LocalDate.of(2020, 2, 9), true, "Pencil", 36, 4.99f, 179.64f),
new Order(LocalDate.of(2020, 2, 26), false, "Pen", 27, 19.99f, 539.73f),
new Order(LocalDate.of(2020, 3, 15), true, "Pencil", 56, 2.99f, 167.44f) //
};
File outFile = new File(filePath);
outFile.getParentFile().mkdirs();
OutputStream outputStream = new FileOutputStream(outFile);
DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
for (Order order : orders) {
dataOutputStream.writeUTF(order.getOrderDate().toString());
dataOutputStream.writeBoolean(order.isFinished());
dataOutputStream.writeUTF(order.getItem());
dataOutputStream.writeInt(order.getUnits());
dataOutputStream.writeFloat(order.getUnitCost());
dataOutputStream.writeFloat(order.getTotal());
}
dataOutputStream.close();
}
}
After running the above example, we have a data file. Its content is quite confusing:
Finally, we use DataInputStream to read the above file.
ReadDataFile_example1.java
package org.o7planning.dataoutputstream.ex;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public class ReadDataFile_example1 {
// Windows: C:/somepath/data-file.txt
private static final String filePath = "/Volumes/Data/test/data-file.txt";
public static void main(String[] args) throws IOException {
File file = new File(filePath);
InputStream inputStream = new FileInputStream(file);
DataInputStream dataInputStream = new DataInputStream(inputStream);
int row = 0;
System.out.printf("|%3s | %-10s | %10s | %-15s | %8s| %10s | %10s |%n", //
"No", "Order Date", "Finished?", "Item", "Units", "Unit Cost", "Total");
System.out.printf("|%3s | %-10s | %10s | %-15s | %8s| %10s | %10s |%n", //
"--", "---------", "----------", "----------", "------", "---------", "---------");
while (dataInputStream.available() > 0) {
row++;
String orderDate = dataInputStream.readUTF();
boolean finished = dataInputStream.readBoolean();
String item = dataInputStream.readUTF();
int units = dataInputStream.readInt();
float unitCost = dataInputStream.readFloat();
float total = dataInputStream.readFloat();
System.out.printf("|%3d | %-10s | %10b | %-15s | %8d| %,10.2f | %,10.2f |%n", //
row, orderDate, finished, item, units, unitCost, total);
}
dataInputStream.close();
}
}
Output:
5. writeBytes(String s)
No ADS
Convert the given String to a sequence of characters, then cast each character to a byte and write to this DataOutputStream using the writeByte(byte) method.
public final void writeBytes(String s) throws IOException
Calling the writeBytes(String) method is equivalent to:
int len = s.length();
for (int i = 0 ; i < len ; i++) {
out.write((byte)s.charAt(i));
}
incCount(len);
6. writeChars(String s)
Convert the given String to a sequence of characters, then write each character in turn to this DataOutputStream using the writeChar(char) method.
public final void writeChars(String s) throws IOException
Calling the writeChars(String) method is equivalent to:
int len = s.length();
for (int i = 0 ; i < len ; i++) {
int v = s.charAt(i);
writeChar(v);
}
7. writeUTF(String str)
No ADS
Write a String to this DataOutputStream with "Modified UTF-8" encoding.
public final void writeUTF(String str) throws IOException
First, two bytes are written to the output stream as if by the writeShort method giving the number of bytes to follow. This value is the number of bytes actually written out, not the length of the string.
For example, call the writeUTF("ÂBC") method to write the string "ÂBC". As is known, UTF-8 uses 1, 2, 3 or 4 bytes to store a character.
- 'Â' --> 2 bytes
- 'B' --> 1 byte
- 'C' --> 1 byte
First, 2 bytes are used to store information about the number of bytes needed to store this string. The next 4 bytes are used to write the string "ÂBC" in "Modified UTF-8" encoding.
- UTF-8
- DataInputStream
8. writeBoolean(boolean v)
public final void writeBoolean(boolean v) throws IOException
The writeBoolean(boolean) method writes a boolean value to this DataOutputStream. If this value is true then (byte)1 will be written to, otherwise (byte)0 will be written to.
9. writeByte(int v)
public final void writeByte(int v) throws IOException
Write a byte to this DataOutputStream.
10. writeShort(int v)
public final void writeShort(int v) throws IOException
The writeShort(int) method writes 2 bytes to this DataOutputStream.
The two bytes written to are:
(byte)(0xff & (v >> 8))
(byte)(0xff & v)
11. writeChar(int v)
public final void writeChar(int v) throws IOException
The writeChar(int) method writes 2 bytes to this DataOutputStream.
The two bytes written to are:
(byte)(0xff & (v >> 8))
(byte)(0xff & v)
12. writeInt(int v)
No ADS
public final void writeInt(int v) throws IOException
The writeInt(int) method writes 4 bytes to this DataOutputStream.
The four bytes written to are:
(byte)(0xff & (v >> 24))
(byte)(0xff & (v >> 16))
(byte)(0xff & (v >> 8))
(byte)(0xff & v)
13. writeLong(long v)
public final void writeLong(long v) throws IOException
The writeLong(long) method writes 8 bytes to this DataOutputStream.
The eight bytes written to are:
(byte)(0xff & (v >> 56))
(byte)(0xff & (v >> 48))
(byte)(0xff & (v >> 40))
(byte)(0xff & (v >> 32))
(byte)(0xff & (v >> 24))
(byte)(0xff & (v >> 16))
(byte)(0xff & (v >> 8))
(byte)(0xff & v)
14. writeFloat(float v)
public final void writeFloat(float v) throws IOException
The writeFloat(float) method writes 4 bytes to this DataOutputStream.
15. writeDouble(double v)
public final void writeDouble(double v) throws IOException
The writeDouble(double) method writes 8 bytes to this DataOutputStream.
16. size()
Returns the number of bytes written to this DataOutputStream, or Integer.MAX_VALUE if the value is actually greater.
public final int size()
Example:
DataOutputStream_size_ex1.java
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
dos.writeByte(111);
System.out.println("Number of bytes: " + dos.size()); // 1
// 1 char = 2 bytes.
dos.writeChars("ÂBC");
System.out.println("Number of bytes: " + dos.size()); // 1 + 2*3 = 7
// 1 char = 2 bytes.
dos.writeChar('A');
System.out.println("Number of bytes: " + dos.size()); // 7 + 2 = 9
// In UTF-8:
// Two bytes of length information is added before the UTF-8 String (See writeUTF methods).
// UTF-8 String: "ÂBC" =4 bytes; 'Â' = 2 bytes, 'B' = 1 byte, 'C' = 1 byte.
dos.writeUTF("ÂBC");
System.out.println("Number of bytes: " + dos.size()); // 9 + 2 + 4 = 15
No ADS
Java IO Tutorials
- Java CharArrayWriter Tutorial with Examples
- Java FilterReader Tutorial with Examples
- Java FilterWriter Tutorial with Examples
- Java PrintStream Tutorial with Examples
- Java BufferedReader Tutorial with Examples
- Java BufferedWriter Tutorial with Examples
- Java StringReader Tutorial with Examples
- Java StringWriter Tutorial with Examples
- Java PipedReader Tutorial with Examples
- Java LineNumberReader Tutorial with Examples
- Java PrintWriter Tutorial with Examples
- Java IO Binary Streams Tutorial with Examples
- Java IO Character Streams Tutorial with Examples
- Java BufferedOutputStream Tutorial with Examples
- Java ByteArrayOutputStream Tutorial with Examples
- Java DataOutputStream Tutorial with Examples
- Java PipedInputStream Tutorial with Examples
- Java OutputStream Tutorial with Examples
- Java ObjectOutputStream Tutorial with Examples
- Java PushbackInputStream Tutorial with Examples
- Java SequenceInputStream Tutorial with Examples
- Java BufferedInputStream Tutorial with Examples
- Java Reader Tutorial with Examples
- Java Writer Tutorial with Examples
- Java FileReader Tutorial with Examples
- Java FileWriter Tutorial with Examples
- Java CharArrayReader Tutorial with Examples
- Java ByteArrayInputStream Tutorial with Examples
- Java DataInputStream Tutorial with Examples
- Java ObjectInputStream Tutorial with Examples
- Java InputStreamReader Tutorial with Examples
- Java OutputStreamWriter Tutorial with Examples
- Java InputStream Tutorial with Examples
- Java FileInputStream Tutorial with Examples
Show More