Java DataInputStream


DataInputStream可以從輸入流中讀取Java基本資料型別值。DataInputStream類包含讀取資料型別值的讀取方法。 例如,要讀取int值,可使用它的readInt()方法; 讀取char值,可使用它的readChar()方法等。它還支援使用readUTF()方法讀取字串。

範例

以下程式碼顯示如何從檔案讀取原始值和字串。

import java.io.DataInputStream;
import java.io.FileInputStream;

public class Main {
  public static void main(String[] args) {
    String srcFile = "primitives.dat";

    try (DataInputStream dis = new DataInputStream(new FileInputStream(srcFile))) {
      // Read the data in the same order they were written 
      int intValue = dis.readInt();
      double doubleValue = dis.readDouble();
      boolean booleanValue = dis.readBoolean();
      String msg = dis.readUTF();

      System.out.println(intValue);
      System.out.println(doubleValue);
      System.out.println(booleanValue);
      System.out.println(msg);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

上面的程式碼生成以下結果。

java.io.FileNotFoundException: primitives.dat (系統找不到指定的檔案。)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(FileInputStream.java:195)
    at java.io.FileInputStream.<init>(FileInputStream.java:138)
    at java.io.FileInputStream.<init>(FileInputStream.java:93)
    at Main.main(Main.java:6)