🔏
Tech
  • 🟢App aspects
    • Software architecture
      • Caching
      • Anti-patterns
      • System X-ability
      • Coupling
      • Event driven architecture
        • Command Query Responsibility Segregation (CQRS)
        • Change Data Capture (CDC)
      • Distributed transactions
      • App dev notes
        • Architecture MVP
      • TEMP. Check list
      • Hexagonal arch
      • Communication
        • REST vs messaging
        • gRPC
        • WebSocket
      • Load balancers
      • Storage limits
      • Event storming
    • Authentication
    • Deployment strategy
  • Databases
    • Classification
    • DB migration tools
    • PostreSQL
    • Decision guidance
    • Index
      • Hash indexes
      • SSTable, LSM-Trees
      • B-Tree
      • Engines, internals
    • Performance
  • System design
    • Interview preparation
      • Plan
        • Instagram
        • Tinder
        • Digital wallet
        • Dropbox
        • Live video streaming
        • Uber
        • Whatsup
        • Tiktok
        • Twitter
        • Proximity service
    • Algorithms
    • Acronyms
  • 🟢Programming languages
    • Java
      • Features
        • Field hiding
        • HashCode() and Equals()
        • Reference types
        • Pass by value
        • Atomic variables
      • Types
      • IO / NIO
        • Java NIO
          • Buffer
          • Channel
        • Java IO: Streams
          • Input streams
            • BufferedInputStream
            • DataInputStream
            • ObjectInputStream
            • FilterInputStream
            • ByteArrayInputStream
        • Java IO: Pipes
        • Java IO: Byte & Char Arrays
        • Java IO: Input Parsing
          • PushbackReader
          • StreamTokenizer
          • LineNumberReader
          • PushbackInputStream
        • System.in, System.out, System.error
        • Java IO: Files
          • FileReader
          • FileWriter
          • FileOutputStream
          • FileInputStream
      • Multithreading
        • Thread liveness
        • False sharing
        • Actor model
        • Singleton
        • Future, CompletableFuture
        • Semaphore
      • Coursera: parallel programming
      • Coursera: concurrent programming
      • Serialization
      • JVM internals
      • Features track
        • Java 8
      • Distributed programming
      • Network
      • Patterns
        • Command
      • Garbage Collectors
        • GC Types
        • How GC works
        • Tools for GC
    • Kotlin
      • Scope functions
      • Inline value classes
      • Coroutines
      • Effective Kotlin
    • Javascript
      • Javascript vs Java
      • TypeScript
    • SQL
      • select for update
    • Python
  • OS components
    • Network
      • TCP/IP model
        • IP address in action
      • OSI model
  • 🟢Specifications
    • JAX-RS
    • REST
      • Multi part
  • 🟢Protocols
    • HTTP
    • OAuth 2.0
    • LDAP
    • SAML
  • 🟢Testing
    • Selenium anatomy
    • Testcafe
  • 🟢Tools
    • JDBC
      • Connection pool
    • Gradle
    • vim
    • git
    • IntelliJ Idea
    • Elastic search
    • Docker
    • Terraform
    • CDK
    • Argo CD
      • app-of-app setup
    • OpenTelemetry
    • Prometheus
    • Kafka
      • Consumer lag
  • 🟢CI
    • CircleCi
  • 🟢Platforms
    • AWS
      • VPC
      • EC2
      • RDS
      • S3
      • IAM
      • CloudWatch
      • CloudTrail
      • ELB
      • SNS
      • Route 53
      • CloudFront
      • Athena
      • EKS
    • Kubernetes
      • Networking
      • RBAC
      • Architecture
      • Pod
        • Resources
      • How to try
      • Kubectl
      • Service
      • Tooling
        • ArgoCD
        • Helm
        • Istio
    • GraalVM
    • Node.js
    • Camunda
      • Service tasks
      • Transactions
      • Performance
      • How it executes
  • 🟢Frameworks
    • Hibernate
      • JPA vs Spring Data
    • Micronaut
    • Spring
      • Security
      • JDBC, JPA, Hibernate
      • Transactions
      • Servlet containers, clients
  • 🟢Awesome
    • Нейробиология
    • Backend
      • System design
    • DevOps
    • Data
    • AI
    • Frontend
    • Mobile
    • Testing
    • Mac
    • Books & courses
      • Path: Java Concurrency
    • Algorithms
      • Competitive programming
    • Processes
    • Finance
    • Electronics
  • 🟢Electronics
    • Arduino
    • IoT
  • Artificial intelligence
    • Artificial Intelligence (AI)
  • 🚀Performance
    • BE
  • 📘Computer science
    • Data structures
      • Array
      • String
      • LinkedList
      • Tree
    • Algorithms
      • HowTo algorithms for interview
  • 🕸️Web dev (Frontend)
    • Trends
    • Web (to change)
  • 📈Data science
    • Time series
Powered by GitBook
On this page
  • Java DataInputStream Example
  • Create a DataInputStream
  • Using a DataInputStream With a DataOutputStream

Was this helpful?

  1. Programming languages
  2. Java
  3. IO / NIO
  4. Java IO: Streams
  5. Input streams

DataInputStream

PreviousBufferedInputStreamNextObjectInputStream

Last updated 2 years ago

Was this helpful?

The Java DataInputStream class, java.io.DataInputStream, enables you to read Java primitives (int, float, long etc.) from an InputStream instead of only raw bytes. You wrap an InputStream in a DataInputStream and then you can read Java primitives via ' the DataInputStream. That is why it is called DataInputStream - because it reads data (numbers) instead of just bytes.

The DataInputStream is handy if the data you need to read consists of Java primitives larger than one byte each, like int, long, float, double etc. The DataInputStream expects the multi byte primitives to be written in network byte order (Big Endian - most significant byte first).

Often you will use a Java DataInputStream to read data written by a .

The Java DataInputStream class is a subclass of InputStream, so DataInputStream also has the basic read methods that enable you to read a single byte or an array of bytes from the underlying InputStream, in case you need that. In this Java DataInputStream tutorial I will only cover the extra methods the DataInputStream has, though.

One issue to keep in mind when reading primitive data types is, that there is no way to distinguish a valid int value of -1 from the normal end-of-stream marker. That basically means, that you cannot see from the primitive value returned if you have reached end-of-stream. Therefore you kind of have to know ahead of time what data types to read, and in what sequence. In other words, you need to know ahead of time what data you can read from the DataInputStream.

Java DataInputStream Example

Here is a Java DataInputStream example:

DataInputStream dataInputStream = new DataInputStream(
                            new FileInputStream("binary.data"));

int    aByte   = input.read();
int    anInt   = input.readInt();
float  aFloat  = input.readFloat();
double aDouble = input.readDouble();
//etc.

input.close();

First a DataInputStream is created with a FileInputStream as source for its data. Second, Java primitives are read from the DataInputStream.

Create a DataInputStream

You create a Java DataInputStream via its constructor. When you do so, you pass an InputStream as parameter from which the primitive data types are to be read. Here is an example of creating a Java DataInputStream:

DataInputStream dataInputStream =
        new DataInputStream(
                new FileInputStream("data/data.bin"));

Using a DataInputStream With a DataOutputStream

As mentioned earlier, the DataInputStream class is often used together with a DataOutputStream. Therefore I just want to show you an example of first writing data with a DataOutputStream and then reading it again with a DataInputStream. Here is the example Java code:

import java.io.*;


public class DataInputStreamExample {

    public static void main(String[] args) throws IOException {
        DataOutputStream dataOutputStream =
                new DataOutputStream(
                        new FileOutputStream("data/data.bin"));

        dataOutputStream.writeInt(123);
        dataOutputStream.writeFloat(123.45F);
        dataOutputStream.writeLong(789);

        dataOutputStream.close();

        DataInputStream dataInputStream =
                new DataInputStream(
                        new FileInputStream("data/data.bin"));

        int   int123     = dataInputStream.readInt();
        float float12345 = dataInputStream.readFloat();
        long  long789    = dataInputStream.readLong();

        dataInputStream.close();

        System.out.println("int123     = " + int123);
        System.out.println("float12345 = " + float12345);
        System.out.println("long789    = " + long789);
    }
}

This example first creates a DataOutputStream and then writes an int, float and a long value to a file. Second the example creates a DataInputStream which reads the int, float and long value in from the same file.

🟢
Java DataOutputStream
Java DataInputStream converts bytes to int, long, float and double from an InputStream