Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Java.io.DataOutputStream in Java
Next article icon

Java.io.DataInputStream class in Java | Set 1

Last Updated : 11 Sep, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

A data input stream enables an application to 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. 

An application uses a data output stream to write data that can later be read by a data input stream. Data input streams and data output streams represent Unicode strings in a format that is a slight modification of UTF-8. DataInputStream is not necessarily safe for multithreaded access. Thread safety is optional and is the responsibility of users of methods in this class.

Firstmost let us do discuss the constructor of this class 

Constructor Action Performed
DataInputStream(InputStream in) Creates a DataInputStream that uses the specified underlying InputStream.

Now let us discuss methods of this class that are depicted below in a tabular format as shown below as follows: 

Methods  Action performed 
read(byte[] b) Reads some number of bytes from the contained input stream and stores them into the buffer array b.
read(byte[] b, int off, int len) Reads up to length bytes of data from the contained input stream into an array of bytes. 
readBoolean() Reads one input byte and returns true if that byte is nonzero, false if that byte is zero. 
readChar() Reads two input bytes and returns a char value. 
readUTF() Reads data from the underlying input stream and converts the bytes into a Unicode string.
readByte() Read one input byte and returns a byte value.
readFloat() Read four input bytes and returns a float value.
readFully() Read bytes equal to the length of the byte array
readDouble() Reads eight input bytes and returns a double value.
readInt() Reads four input bytes and returns an int value. 
readLine() Reading lines of text
readLong() Reading eight input bytes and returns a long value
readShort() Read two input bytes and return a short value.
readUnsignedByte() Read byte and return as an integer
readUnsignedShort() Read two input bytes and returns as an integer array
skipBytes() Skips over n bytes of data from input stream

Remember: The DataInputStream class is often used together with a DataOutputStream.

Implementation:

Now let us do implement a few of the above methods of this class has been discussed above

Below program uses try-with-resources. It requires JDK 7 or later as concept of try-catch block was introduced in Java7

Example 1 

Java




// Java program to Demonstrate DataInputStream Class
  
// Importing I/O classes
import java.io.*;
  
// Main class
class DataInputStreamDemo {
  
    // Main driver method
    public static void main(String args[]) throws IOException {
  
        // Writing the data
  
        // Try block to check for exceptions
        try ( DataOutputStream dout =
                        new DataOutputStream(new FileOutputStream("file.dat")) ) {
  
            dout.writeDouble(1.1);
            dout.writeInt(55);
            dout.writeBoolean(true);
            dout.writeChar('4');
        }
  
        // Catch block to handle the exceptions
        catch (FileNotFoundException ex) {
  
            // Display message when FileNotFoundException occurs
            System.out.println("Cannot Open the Output File");
            return;
        }
  
        // Reading the data back.
  
        // Try block to check for exceptions
        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();
  
            // Print the values
            System.out.println("Values: " + a + " " + b + " " + c + " " + d);
        }
  
        // Catch block to handle the exceptions
        catch (FileNotFoundException e) {
  
            // Display message when FileNotFoundException occurs
            System.out.println("Cannot Open the Input File");
            return;
        }
    }
}
 
 

Output:

Notice how there is no longer any explicit close() method call. The try-with-resources construct takes care of that.
Next Article: Java.io.DataInputStream class in Java | Set 2



Next Article
Java.io.DataOutputStream in Java

N

Nishant Sharma
Improve
Article Tags :
  • Java
  • Java-I/O
Practice Tags :
  • Java

Similar Reads

  • Java.io.DataInputStream class in Java | Set 2
    Java.io.DataInputStream class in Java | Set 1 More Methods: byte readByte() : Reads and returns one input byte. Syntax:public final byte readByte() throws IOException Returns: the next byte of this input stream as a signed 8-bit byte. Throws: EOFException IOException float readFloat() : Reads four i
    3 min read
  • Java.io.FilterInputStream Class in Java
    Filter Streams filters data as they read and write data in the Input Stream, filters it and pass it on to the underlying Streams. Filter Streams are FilterInputStream FilterOutput Stream FilterInputStream : Java.io.FilterInputStream class works almost like InputStream class in Java but what it does
    9 min read
  • Java.io.InputStream Class in Java
    Java InputStream class is the superclass of all the io classes i.e. representing an input stream of bytes. It represents an input stream of bytes. Applications that are defining a subclass of the Java InputStream class must provide a method, that returns the next byte of input. A reset() method is i
    3 min read
  • Java.util.zip.DeflaterInputStream class in Java
    Implements an input stream filter for compressing data in the "deflate" compression format. Constructor and Description DeflaterInputStream(InputStream in) : Creates a new input stream with a default compressor and buffer size. DeflaterInputStream(InputStream in, Deflater defl) : Creates a new input
    3 min read
  • Java.io.DataOutputStream in Java
    A data output stream lets an application write primitive Java data types to an output stream in a portable way. An application can then use a data input stream to read the data back in. Let us do discuss the constructor of this class prior to moving ahead to the methods of this class. Constructor: D
    5 min read
  • Java.io.FilterOutputStream Class in Java
    java.io.FilterInputStream Class in Java Java.io.FilterOutputStream class is the superclass of all those classes which filters output streams. The write() method of FilterOutputStream Class filters the data and write it to the underlying stream, filtering which is done depending on the Streams. Decla
    5 min read
  • Java.util.zip.GZIPInputStream class in Java
    This class implements a stream filter for reading compressed data in the GZIP file format. Constructors GZIPInputStream(InputStream in) : Creates a new input stream with a default buffer size. GZIPInputStream(InputStream in, int size) : Creates a new input stream with the specified buffer size. Meth
    2 min read
  • Java.util.jar.JarInputStream class in Java
    The JarInputStream class is used to read the contents of a JAR file from any input stream. It extends the class java.util.zip.ZipInputStream with support for reading an optional Manifest entry. The Manifest can be used to store meta-information about the JAR file and its entries. Constructors JarInp
    3 min read
  • Java.io.FilterReader class in Java
    Abstract class for reading filtered character streams. The abstract class FilterReader itself provides default methods that pass all requests to the contained stream. Subclasses of FilterReader should override some of these methods and may also provide additional methods and fields. Constructor : pr
    3 min read
  • Java.util.zip.InflaterInputStream class in Java
    This class implements a stream filter for uncompressing data in the "deflate" compression format. It is also used as the basis for other decompression filters, such as GZIPInputStream. Constructors InflaterInputStream(InputStream in) : Creates a new input stream with a default decompressor and buffe
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences