Java IO Data Streams - RameshMF/java-io-guide GitHub Wiki
Data Streams Overview
Data streams support binary I/O of primitive data type values (boolean, char, byte, short, int, long, float, and double) as well as String values. All data streams implement either the DataInput interface or the DataOutput interface.
This guide focuses on the most widely-used implementations of these interfaces, DataInputStream and DataOutputStream.
DataInputStream Class
Java DataInputStream class allows an application to read primitive data from the input stream in a machine-independent way. Java application generally uses the data output stream to write data that can later be read by a data input stream.
DataInputStream Class Example
package com.javaguides.javaio.fileoperations.examples;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public class DataInputStreamExample {
public static void main(String[] args) {
try(InputStream input = new FileInputStream("C:/workspace/sample.txt");
DataInputStream inst = new DataInputStream(input);){
int count = input.available();
byte[] ary = new byte[count];
inst.read(ary);
for (byte bt : ary) {
char k = (char) bt;
System.out.print(k+"-");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
DataOutputStream Class
Java DataOutputStream class allows an application to write primitive Java data types to the output stream in a machine-independent way.
Java application generally uses the data output stream to write data that can later be read by a data input stream.
DataOutputStream Class Example
package com.javaguides.javaio.fileoperations.examples;
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DataOutputStreamExample {
private static final Logger LOGGER = LoggerFactory.getLogger(DataOutputStreamExample.class);
public static void main(String[] args) {
final double[] prices = { 19.99, 9.99, 15.99, 3.99, 4.99 };
final int[] units = { 12, 8, 13, 29, 50 };
final String[] descs = { "Java T-shirt", "Java Mug",
"Duke Juggling Dolls", "Java Pin", "Java Key Chain" };
try (DataOutputStream out = new DataOutputStream(
new BufferedOutputStream(new FileOutputStream("C:/Project_Work/workspace/java-io-guide/sample.txt")))) {
for (int i = 0; i < prices.length; i++) {
out.writeDouble(prices[i]);
out.writeInt(units[i]);
out.writeUTF(descs[i]);
}
} catch (IOException e) {
LOGGER.error(e.getMessage());
}
}
}