Java DataInputStream Class

Java 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.


Java DataInputStream class declaration

Let’s see the declaration for java.io.DataInputStream class:

  1. 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 read len bytes 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 a string that 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 buffer array.
void readFully(byte[] b, int off, int len) It is used to read len bytes from the input stream.

 

Example of DataInputStream class

In this example, we are reading the data from the file testout.txt file.

  1. package com.javatpoint;
  2. import java.io.*;
  3. public class DataStreamExample {
  4.   public static void main(String[] args) throws IOException {
  5.     InputStream input = new FileInputStream(“D:\\testout.txt”);
  6.     DataInputStream inst = new DataInputStream(input);
  7.     int count = input.available();
  8.     byte[] ary = new byte[count];
  9.     inst.read(ary);
  10.     for (byte bt : ary) {
  11.       char k = (char) bt;
  12.       System.out.print(k+“-“);
  13.     }
  14.   }
  15. }

Here, we are assuming that you have following data in “testout.txt” file:

JAVA

Output:

J-A-V-A
java for beginners
java for beginners
java for beginners
CodSir //course // books
...

WikiSir

Java 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. Java DataInputStream class declaration Let’s see the declaration for java.io.DataInputStream class: public class DataInputStream extends FilterInputStream implements DataInput Java […]

Tags:

....
...