The Wayback Machine - http://web.archive.org/web/20200219201200/https://www.geeksforgeeks.org/java-io-datainputstream-class-java-set-1/amp/

Java.io.DataInputStream class in Java | Set 1

A data input stream enable an application read primitive Java data types from an underlying input stream in a machine-independent way(instead of raw bytes). That is why it is called DataInputStream – because it reads data (numbers) instead of just bytes.

Constructor:

Important Methods:



The DataInputStream class is often used together with a DataOutputStream.

Implementations of some of the important methods
Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

//Java program to demonstrate DataInputStream
// This program uses try-with-resources. It requires JDK 7 or later.
import java.io.*;
class DataInputStreamDemo 
{
    public static void main(String args[]) throws IOException 
    {
        //writing the data.
        try ( DataOutputStream dout =
                    new DataOutputStream(new FileOutputStream("file.dat")) )
        {
            dout.writeDouble(1.1);
            dout.writeInt(55);
            dout.writeBoolean(true);
            dout.writeChar('4');
        }
          
        catch(FileNotFoundException ex)
        {
            System.out.println("Cannot Open the Output File");
            return;
        }
          
        // reading the data back.
        try ( DataInputStream din =
                    new DataInputStream(new FileInputStream("file.dat")) )
        {
   
                         //illustrating readDouble() method
            double a = din.readDouble();
                         //illustrating readInt() method
            int b = din.readInt();
                         //illustrating readBoolean() method
            boolean c = din.readBoolean();
                         //illustrating readChar() method
            char d=din.readChar();
            System.out.println("Values: " + a + " " + b + " " + c+" " + d);
        }
        catch(FileNotFoundException e)
        {
            System.out.println("Cannot Open the Input File");
            return;
        }
    }
}
chevron_right

Notice how there is no longer any explicit close() method call. The try-with-resources construct takes care of that.

Output:

Values: 1.1 55 true 4

Next Article: Java.io.DataInputStream class in Java | Set 2

This article is contributed by Nishant Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



Article Tags :
Practice Tags :