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:
DataInputStream readChar() method in Java with Examples
Next article icon

DataInputStream read() method in Java with Examples

Last Updated : 05 Jun, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report

The read() method of DataInputStream class in Java is of two types:

  1. read(byte[] b) method of DataInputStream class in Java is used to read bytes from the input stream and store them into the buffer byte array.This read() method returns the number of bytes actually read as an integer type. This method returns -1 if the input stream is ended and no more data is available to read. This method throws an exception if the byte array is null.

    Syntax:

      public final int read(byte[] b)                 throws IOException  

    Overrides: This method overrides the read() method of FilterInputStream class.

    Parameters: This method accepts one parameter b which represents the byte array into which the data is to read.

    Return value: This method returns the number of bytes actually read. It returns -1 if the input stream is ended and no more data is available to read.

    Exceptions:

    • NullPointerException – It throws NullPointerException if byte array is null.
    • IOException – This method throws IOException if the stream is closed or some other I/O error occurs.

    Below program illustrates read(byte[]) method in DataInputStream class in IO package:

    Program: Assume the existence of file “c:/demo.txt”.




    // Java program to illustrate
    // DataInputStream read(byte[]) method
    import java.io.*;
    public class GFG {
        public static void main(String[] args)
            throws IOException
        {
      
            // Create input stream 'demo.txt'
            // for reading containing
            // text "GEEKSFORGEEKS"
            FileInputStream inputStream
                = new FileInputStream(
                    "c:/demo.txt");
      
            // Convert inputStream to
            // DataInputStream
            DataInputStream dataInputStr
                = new DataInputStream(
                    inputStream);
      
            // Count the total bytes
            // form the input stream
            int count = inputStream.available();
      
            // Create byte array
            byte[] b = new byte[count];
      
            // Read data into byte array
            int bytes = dataInputStr.read(b);
      
            // Print number of bytes
            // actually read
            System.out.println(bytes);
      
            for (byte by : b) {
                // Print the character
                System.out.print((char)by);
            }
        }
    }
     
     
    Input:
    Output:
  2. read(byte[] b, int offset, int length) method of DataInputStream class in Java is used to read specified number of bytes from the input stream and store them into the buffer byte array.This read() method returns the number of bytes actually read as an integer type. This method returns -1 if the input stream is ended and no more data is available to read. This method throws an exception if the byte array is null.

    Syntax:

      public final int read(byte[] b,                        int offset,                        int length)                 throws IOException  

    Overrides: This method overrides the read() method of FilterInputStream class.

    Parameters: This method accepts three parameters:

    • b – It represents the byte array into which the data is to read.
    • offset – It represents the starting index in the byte array.
    • length – It represents the total number of bytes to be read.

    Return value: This method returns the number of bytes actually read. It returns -1 if the input stream is ended and no more data is available to read.

    Exceptions:

    • NullPointerException – It throws NullPointerException if byte array is null.
    • IndexOutOfBoundsException – It throws IndexOutOfBoundsException if If offset is negative or length is negative or length is greater than the difference of length of byte array and offset.
    • IOException – This method throws IOException if the stream is closed or some other I/O error occurs.

    Below program illustrates read(byte[], int, int) method in DataInputStream class in IO package:

    Program: Assume the existence of file “c:/demo.txt”.




    // Java program to illustrate
    // DataInputStream read(byte[], int, int) method
    import java.io.*;
    public class GFG {
        public static void main(String[] args)
            throws IOException
        {
      
            // Create input stream 'demo.txt'
            // for reading containing
            // text "GEEKSFORGEEKS"
            FileInputStream inputStream
                = new FileInputStream(
                    "c:/demo.txt");
      
            // Convert inputStream to
            // DataInputStream
            DataInputStream dataInputStr
                = new DataInputStream(
                    inputStream);
      
            // Count the total bytes
            // form the input stream
            int count = inputStream.available();
      
            // Create byte array
            byte[] b = new byte[count];
      
            // Read data into byte array
            int bytes = dataInputStr.read(b, 4, 5);
      
            // Print number of bytes
            // actually read
            System.out.println(bytes);
      
            for (byte by : b) {
                // Print the character
                System.out.print((char)by);
            }
        }
    }
     
     
    Input:
    Output:

References:
1. https://docs.oracle.com/javase/10/docs/api/java/io/DataInputStream.html#read(byte%5B%5D)
2. https://docs.oracle.com/javase/10/docs/api/java/io/DataInputStream.html#read(byte%5B%5D, int, int)



Next Article
DataInputStream readChar() method in Java with Examples

P

pp_pankaj
Improve
Article Tags :
  • Java
  • Java-Functions
  • Java-IO package
Practice Tags :
  • Java

Similar Reads

  • DataInputStream readInt() method in Java with Examples
    The readInt() method of DataInputStream class in Java is used to read four input bytes and returns a integer value. This method reads the next four bytes from the input stream and interprets it into integer type and returns. Syntax: public final int readInt() throws IOException Specified By: This me
    2 min read
  • DataInputStream readByte() method in Java with Examples
    The readByte() method of DataInputStream class in Java is used to read and return one input byte. The byte is a signed value in the range from -128 to +127. The bytes in this method are read from the accommodated input stream. Syntax: public final byte readByte() throws IOException Specified By: Thi
    2 min read
  • DataInputStream readLong() method in Java with Examples
    The readLong() method of DataInputStream class in Java is used to read eight input bytes and returns a long value. This method reads the next eight bytes from the input stream and interprets it into long type and returns. Syntax: public final long readLong() throws IOException Specified By: This met
    2 min read
  • DataInputStream readChar() method in Java with Examples
    The readChar() method of DataInputStream class in Java is used to read two input bytes and returns a char value. This method basically reads the bytes as character that are written by writechar() method of DataOutputStream class. Syntax: public final char readChar() throws IOException Specified By:
    2 min read
  • DataInputStream readFully() method in Java with Examples
    The readFully() method of DataInputStream class in Java is of two types: readFully(byte[] b) method of DataInputStream class in Java is used to read bytes equal to the length of byte array b from an input stream and store them into the byte array b. General Contract: The readFully(byte[] b) method i
    4 min read
  • DataInputStream readShort() method in Java with Examples
    The readShort() method of DataInputStream class in Java is used to read two input bytes and returns a short value. This method reads the next two bytes from the input stream and interprets it into short type and returns. Syntax: public final short readShort() throws IOException Specified By: This me
    2 min read
  • DataInputStream readFloat() method in Java with Examples
    The readFloat() method of DataInputStream class in Java is used to read four input bytes and returns a float value. This method reads the next four bytes from the input stream and interprets it into float type and returns. Syntax: public final float readFloat() throws IOException Specified By: This
    2 min read
  • DataInputStream readDouble() method in Java with Examples
    The readDouble() method of DataInputStream class in Java is used to read eight input bytes and returns a double value. This method reads the next eight bytes from the input stream and interprets it into double type and returns. Syntax: public final double readDouble() throws IOException Specified By
    2 min read
  • DataInputStream readBoolean() method in Java with Examples
    The readBoolean() method of DataInputStream class in Java is used to read one input byte and if the byte read is zero this method returns false and if the byte read is nonzero then this method returns true. Syntax: public final boolean readBoolean() throws IOException Specified By: This method is sp
    2 min read
  • ByteArrayInputStream read() method in Java with Examples
    The read() method of ByteArrayInputStream class in Java is used in two ways: 1. The read() method of ByteArrayInputStream class in Java is used to read the next byte of the ByteArrayInputStream. This read() method returns the byte that is read into the form of an integer and if the input stream is e
    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