DataInputStream Example

suggest change

DataInputStream adds reads for Java primitives (readInt, readUTF, and so on). This example only reads raw bytes from a file. available() is an estimate, not a reliable length, so the size comes from the file. readFully reads every byte or throws. A byte is signed, so mask it before casting to char.

package com.streams;
import java.io.*;
public class DataStreamDemo {
  public static void main(String[] args) throws IOException {
    File file = new File("D:\\datastreamdemo.txt");
    try (DataInputStream inst = new DataInputStream(new FileInputStream(file))) {
      byte[] arr = new byte[(int) file.length()];
      inst.readFully(arr);
      for (byte byt : arr) {
        char ki = (char) (byt & 0xFF);
        System.out.print(ki + "-");
      }
    }
  }
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents