Java I/O How to - Read float/long/char/byte/int/double/UTF/boolean from a file








Question

We would like to know how to read float/long/char/byte/int/double/UTF/boolean from a file.

Answer

/*from  w w  w .  j a v a 2s  .  c o m*/
import java.io.DataInputStream;
import java.io.FileInputStream;

public class Main {

  public static void main(String[] args) throws Exception {
    FileInputStream fin = new FileInputStream("myfile.dat");

    DataInputStream din = new DataInputStream(fin);
    while (true) {
      int theNumber = din.readInt();
      //double theNumber = din.readDouble();
      //System.out.println(din.readUTF());
      //boolean b = din.readBoolean();
      byte b = din.readByte();
            System.out.println("byte : " + b);
      System.out.println(theNumber);
      
      char ch = din.readChar();
            System.out.println("Char : " + ch);
            float f = din.readFloat();
            System.out.println("float : " + f);
            long l = din.readLong();
            System.out.println("long : " + l);
            
    }
  }
}