Java Datainputstream Class - Java Tutorial

Java Datainputstream Class

BLUF: Mastering Java Datainputstream Class is a key requirement for any Java developer. This lesson breaks down the object-oriented principles and syntax required to use this concept in real-world applications.
Write Once, Run Anywhere Tip: Java Datainputstream Class

Java's versatility is unmatched. Learn how Java Datainputstream Class fits into the Java ecosystem and improves your code structure in the tutorial below.

The Java DataInputStream class enables a program to retrieve primitive data from an input stream in a manner that is independent of the underlying machine.

In Java programming, a common practice is to utilize the DataOutputStream to store data that can be retrieved later using a DataInputStream.

Java DataInputStream class declaration

Now, let's examine the declaration of the java.io.DataInputStream class:

Example

public class DataInputStream extends FilterInputStream implements DataInput

Java DataInputStream class Methods

Method Description
int read(byte[] b) It is used to read the number of bytes from the input stream.
int read(byte[] b, int off, int len) It is used to readlenbytes of data from the input stream.
int readInt() It is used to read input bytes and return an int value.
byte readByte() It is used to read and return the one input byte.
char readChar() It is used to read two input bytes and returns a char value.
double readDouble() It is used to read eight input bytes and returns a double value.
boolean readBoolean() It is used to read one input byte and return true if byte is non zero, false if byte is zero.
int skipBytes(int x) It is used to skip over x bytes of data from the input stream.
String readUTF() It is used to read astringthat has been encoded using the UTF-8 format.
void readFully(byte[] b) It is used to read bytes from the input stream and store them into the bufferarray.
void readFully(byte[] b, int off, int len) It is used to readlenbytes from the input stream.

Example of DataInputStream class

In this instance, we are retrieving information from the testout.txt file.

Example

package com.example;

import java.io.*;  

public class DataStreamExample {

  public static void main(String[] args) throws IOException {

    InputStream input = new FileInputStream("D:\\testout.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+"-");

    }

  }

}

In this scenario, it is presumed that the data is present in a file named "testout.txt":

Output:

Output

J-A-V-A

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience