Read byte array from file using DataInputStream - Java File Path IO

Java examples for File Path IO:DataInputStream

Introduction

To read an array of bytes from file, use int read(byte b[]) method of Java DataInputStream class.

This method reads bytes from input stream and store them in array of bytes.

read(byte b[]) method returns number of bytes read.

Demo Code

import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class Main {

  public static void main(String[] args) {

    String strFilePath = "C:/Folder/readByteArray.txt";

    try {//w w w . ja  v a2 s . c om
      FileInputStream fin = new FileInputStream(strFilePath);

      DataInputStream din = new DataInputStream(fin);

      byte b[] = new byte[10];
      din.read(b);

      din.close();

    } catch (FileNotFoundException fe) {
      System.out.println("FileNotFoundException : " + fe);
    } catch (IOException ioe) {
      System.out.println("IOException : " + ioe);
    }
  }
}

Result


Related Tutorials