This Java tutorial helps you understand and use the data stream classes DataInputStream and DataOutputStream in the Java File I/O API.

You use data streams to read and write primitive types and String values in binary format. DataInput and DataOutput are the base interfaces for all data streams in the standard Java File I/O API. And DataInputStream and DataOutputStream are the two widely-used implementations. The following class diagram illustrates how data streams relate to byte streams:

DataStreamsAPI

 

1. DataInputStream Reading Operations

As you can see, the DataInputStream class is descended from the InputStream class so it has all behaviors of a byte input stream. In addition, it implements the DataInput interface which defines the following read operations for primitive types and Strings:

  • readBoolean(): Reads one input byte and returns true if that byte is nonzero, false if that byte is zero.
  • readByte(): Reads and returns one input byte.
  • readChar(): Reads 2 input bytes and returns a char value.
  • readDouble():Reads 8 input bytes and returns a double value.
  • readFloat(): Reads 4 input bytes and returns a float value.
  • readInt(): Reads 4 input bytes and returns an int value.
  • readLong(): Reads 8 input bytes and returns a long value.
  • readShort(): Reads 2 input bytes and returns a short value.
  • readUTF(): Reads in a string that has been encoded using a modified UTF-8 format.

Note that each read method reads a number of bytes equivalent to the size of the primitive type (except String).

You can construct a DataInputStream object by wrapping an InputStream. For example:

DataInputStream dataInput = new DataInputStream(new FileInputStream(inputFile));

 

2. DataInputStream Writing Operations

Likewise, a DataOutputStream class is descended from the OutputStream class so it inherits all behaviors of a byte output stream. In addition, it implements the DataOutput interface which defines the following write operations for primitive types and Strings:

  • writeBoolean(boolean v): Writes a boolean to the underlying output stream as a 1-byte value.
  • writeByte(int v): Writes out a byte to the underlying output stream as a 1-byte value.
  • writeBytes(String s): Writes out the string to the underlying output stream as a sequence of bytes.
  • writeChar(int v): Writes a char to the underlying output stream as a 2-byte value, high byte first.
  • writeChars(String s): Writes a string to the underlying output stream as a sequence of characters.
  • writeDouble(double v): Converts the double argument to a long using the doubleToLongBits method in class Double, and then writes that long value to the underlying output stream as an 8-byte quantity, high byte first.
  • writeFloat(float v): Converts the float argument to an int using the floatToIntBits method in class Float, and then writes that int value to the underlying output stream as a 4-byte quantity, high byte first.
  • writeInt(int v): Writes an int to the underlying output stream as four bytes, high byte first.
  • writeLong(long v): Writes a long to the underlying output stream as eight bytes, high byte first.
  • writeShort(int v): Writes a short to the underlying output stream as two bytes, high byte first.
  • writeUTF(String str): Writes a string to the underlying output stream using modified UTF-8 encoding in a machine-independent manner.

Note that each write method writes a number of bytes equivalent to the size of the primitive type (except String).

You can create a DataOutputStream object by wrapping an OutputStream like this:

DataOutputStream dataOutput = new DataOutputStream(new FileOutputStream(outputFile));

Data streams are perfect for implementing simple flat-file database from scratch. Let’s see a couple of examples.

 

3. Writing a File by Using DataOutputStream

The following program stores records of some students to a file whose path is given from a command-line argument:

import java.util.*;
import java.io.*;

/**
 * StudentRecordWriter.java
 * This program illustrates how to use the DataOutputStream class for writing
 * data to a file.
 *
 * @author www.codejava.net
 */
public class StudentRecordWriter {
	DataOutputStream dataOutput;

	public StudentRecordWriter(String outputFile) throws IOException {
		dataOutput = new DataOutputStream(new FileOutputStream(outputFile));
	}

	public void write(Student student) throws IOException {
		dataOutput.writeUTF(student.getName());
		dataOutput.writeBoolean(student.getGender());
		dataOutput.writeInt(student.getAge());
		dataOutput.writeFloat(student.getGrade());
	}

	public void save() throws IOException {
		dataOutput.close();
	}

	public static void main(String[] args) {
		if (args.length < 1) {
			System.out.println("Please provide output file");
			System.exit(0);
		}

		String outputFile = args[0];

		List<Student> listStudent = new ArrayList<>();

		listStudent.add(new Student("Alice", false, 23, 80.5f));
		listStudent.add(new Student("Brian", true, 22, 95.0f));
		listStudent.add(new Student("Carol", false, 21, 79.8f));

		try {
			StudentRecordWriter writer = new StudentRecordWriter(outputFile);

			for (Student student : listStudent) {
				writer.write(student);
			}

			writer.save();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}
}

And here’s code of the Student class:

/**
 * Student.java
 * This class represents a Student
 *
 * @author www.codejava.net
 */
public class Student {
	private String name;
	private boolean gender;	// true is male, false is female
	private int age;
	private float grade;

	public Student() {
	}

	public Student(String name, boolean gender, int age, float grade) {
		this.name = name;
		this.gender = gender;
		this.age = age;
		this.grade = grade;
	}

	public String getName() {
		return this.name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public boolean getGender() {
		return this.gender;
	}

	public void setGender(boolean gender) {
		this.gender = gender;
	}

	public int getAge() {
		return this.age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public float getGrade() {
		return this.grade;
	}

	public void setGrade(float grade) {
		this.grade = grade;
	}
}

Run the StudentRecordWriter program using command line like this:

java StudentRecordWriter student.dat

You will see a file named student.dat created, but it is in binary format, which means you cannot view its content using a text editor.

 

4. Reading a File by Using DataInputStream

And the following program reads all records from a given file and converts them back to a list of Student objects:

import java.util.*;
import java.io.*;

/**
 * StudentRecordReader.java
 * This program illustrates how to use the DataInputStream class for reading
 * data from a file.
 *
 * @author www.codejava.net
 */
public class StudentRecordReader {

	DataInputStream dataInput;

	public StudentRecordReader(String inputFile) throws IOException {
		dataInput = new DataInputStream(new FileInputStream(inputFile));
	}

	public List<Student> readAll() throws IOException {
		List<Student> listStudent = new ArrayList<>();

		try {
			while (true) {
				String name = dataInput.readUTF();
				boolean gender = dataInput.readBoolean();
				int age = dataInput.readInt();
				float grade = dataInput.readFloat();

				Student student = new Student(name, gender, age, grade);
				listStudent.add(student);
			}
		} catch (EOFException ex) {
			// reach end of file
		}

		dataInput.close();

		return listStudent;
	}

	public static void main(String[] args) {
		if (args.length < 1) {
			System.out.println("Please provide input file");
			System.exit(0);
		}

		String inputFile = args[0];

		try {
			StudentRecordReader reader = new StudentRecordReader(inputFile);

			List<Student> listStudent = reader.readAll();

			for (Student student : listStudent) {
				System.out.print(student.getName() + "\t");
				System.out.print(student.getGender() + "\t");
				System.out.print(student.getAge() + "\t");
				System.out.println(student.getGrade());
			}
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}
}

Run this program via command line like this:

java StudentRecordReader student.dat

Output:

Alice   false   23      80.5
Brian   true    22      95.0
Carol   false   21      79.8

 

API References:

 

Related Java File IO Tutorial:

 

Other Java File IO Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.



Add comment

   


Comments 

#2deepak2021-06-08 21:52
This is a really helpful tutorial. Keep it up.
Quote
#1Skankhunt422019-01-20 18:05
This was really helpful, thank you !
Quote