Primitive Data Type Read
import java.io.Closeable; 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 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);/*from ww w . j ava 2s . c o m*/ } catch (FileNotFoundException e) { FileUtil.printFileNotFoundMsg(srcFile); } catch (IOException e) { e.printStackTrace(); } } } class FileUtil { // Prints the location details of a file public static void printFileNotFoundMsg(String fileName) { String workingDir = System.getProperty("user.dir"); System.out.println("Could not find the file '" + fileName + "' in '" + workingDir + "' directory "); } // Closes a Closeable resource such as an input/output stream public static void close(Closeable resource) { if (resource != null) { try { resource.close(); } catch (IOException e) { e.printStackTrace(); } } } }