java tutorial - Java - DataInputStream class and its methods - java programming - learn java - java basics - java for beginners



Java data input stream class

Learn Java - Java tutorial - Java data input stream class - Java examples - Java programs

DataInputStream is used to read primitive data types.

Below is the constructor for creating an InputStream:

InputStream in = DataInputStream(InputStream in);
click below button to copy the code. By - java tutorial - team

Methods

If you use the DataInputStream object, then you have on hand ancillary methods that you can use to read the stream or perform other operations on the thread.

no Method and Description
1 public final int read (byte [] r, int off, int len) throws IOException
Reading up to len bytes of data from the input stream to an array of bytes. Returns the total number of bytes read into the buffer, otherwise -1, if this is the end of the file.
2 public final int read (byte [] b) throws IOException
Reads some bytes from the input stream and stores it in an array of bytes. Returns the total number of bytes read into the buffer, otherwise -1, if this is the end of the file.
3(1) public final Boolean readBooolean()throws IOException
(2) public final byte readByte()throws IOException
(3) public final short readShort()throws IOException
(4) public final Int readInt()throws IOException
These methods will read the bytes from the contents of the InputStream.And returns the next two bytes of the InputStream.
4 public String readLine () throws IOException
Reads the next line of the text from the input stream. The method reads the bytes in sequence, converting each byte separately into a symbol until it encounters line delimiter or end of the file; read characters are then returned as a string.

Sample Code

The following is an example of demonstrating DataInputStream and DataOutputStream. In this example, the test.txt file is written and read from the specified file.

import java.io.*;
public class TestByteStream {

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

      // Write a string to a file in UTF-8 encoding
      DataOutputStream dataOutput = new DataOutputStream(new FileOutputStream("E:\\test.txt"));
      dataOutput.writeUTF("Welcome to wikitechy.com");

      // Read data from the same file
      DataInputStream dataInput = new DataInputStream(new FileInputStream("E:\\test.txt"));

      while(dataInput.available() > 0) {
         String a = dataInput.readUTF();
         System.out.print(a);
      }
   }
}
click below button to copy the code. By - java tutorial - team

Output

Welcome to wikitechy.com

Related Searches to Java - DataInputStream class and its methods