Easy Tutorial
❮ Dir Search Collection Hashtable Key ❯

Java DataInputStream Class

Java Streams


The DataInputStream class allows applications to read primitive Java data types from an underlying input stream in a machine-independent manner.

The following constructor is used to create a DataInputStream object.

DataInputStream dis = new DataInputStream(InputStream in);

Another way to create it is by receiving a byte array and two integer variables, off and len, where off indicates the first byte to read, and len indicates the length of the bytes to read.

No. Method Description
1 public final int read(byte[] r, int off, int len) throws IOException <br> Reads len bytes from the included input stream into a byte array. If len is -1, it returns the number of bytes read.
2 public final int read(byte[] b) throws IOException <br> Reads a certain number of bytes from the included input stream and stores them in the buffer array b.
3 public final Boolean readBoolean() throws IOException, <br> public final byte readByte() throws IOException, <br> public final short readShort() throws IOException, <br> public final int readInt() throws IOException <br> Reads bytes from the input stream and returns the input stream's two bytes as the corresponding primitive data type return value.
4 public String readLine() throws IOException <br> Reads the next text line from the input stream.

Example

The following example demonstrates the use of DataInputStream and DataOutputStream. It reads 5 lines from the text file test.txt, converts them to uppercase, and finally saves them in another file test1.txt.

The content of the test.txt file is as follows:

tutorialpro1
tutorialpro2
tutorialpro3
tutorialpro4
tutorialpro5

Example

import java.io.*;

public class Test {
   public static void main(String args[]) throws IOException {
      DataInputStream in = new DataInputStream(new FileInputStream("test.txt"));
      DataOutputStream out = new DataOutputStream(new FileOutputStream("test1.txt"));
      BufferedReader d = new BufferedReader(new InputStreamReader(in));

      String count;
      while ((count = d.readLine()) != null) {
          String u = count.toUpperCase();
          System.out.println(u);
          out.writeBytes(u + "  ,");
      }
      d.close();
      out.close();
   }
}

The above example compiles and runs with the following result:

tutorialpro1
tutorialpro2
tutorialpro3
tutorialpro4
tutorialpro5

Java Streams

❮ Dir Search Collection Hashtable Key ❯