How to read file in Java – DataInputStream

1. Overview

In this example, we will DataInputStream class to read a file. A data input stream lets an application read primitive Java data types from an underlying input stream in a machine-independent way. An application uses a data output stream to write data that can later be read by a data input stream.
The readLine() from the type DataInputStream is deprecated. Sun officially announced this method cannot convert the property from bytes to characters. It’s advised to use BufferedReader.

2. Read File Using DataInputStream Example

Let's read file character by character. If you want to read file line by line then prefer BufferedReader.
package com.javaguides.javaio.fileoperations.examples;


 * This Java program demonstrates how to read file in Java – DataInputStream.
 * @author

public class DataInputStreamExample {
 public static void main(String[] args) {
  try(InputStream input = new FileInputStream("C:/sample.txt");  
     DataInputStream inst = new DataInputStream(input);){  
     int count = input.available(); 
     byte[] ary = new byte[count];;  
     for (byte bt : ary) {  
       char k = (char) bt;  
     } catch (IOException e) {

3. Reference

Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours

Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course