/* * T03n06.java -- Use DataInputStream to read a binary file of ints * The ints will be read from the file created in the previous example. * DataInputStream is the counterpart of DataOutputStream, and has an * input counterpart to the output methods of DataOutputStream. * * If you've seen the previous example, the only new thing is the method * for computing the number of ints to read from the file; there's a * detailed comment about that in the code. */ import java.io.*; public class T03n06 { public static void main (String [] args) { final String fileName = "T03n05.out"; File fileRef; FileInputStream byteStream; DataInputStream intStream = null; int[] scores; int numOfInts; System.out.println("Reading an array of ints from the file '" + fileName + "'..."); try { fileRef = new File(fileName); byteStream = new FileInputStream(fileRef); intStream = new DataInputStream(byteStream); /* We have a file the holds only ints, and an int is always * 4 bytes in size. So, the number of ints that we need * to read (and thus the size of the array) is one-quarter * of the number of bytes in the file. */ numOfInts = (int) fileRef.length() / 4; scores = new int [numOfInts]; for (int i = 0; i < numOfInts; i++) { scores[i] = intStream.readInt(); } intStream.close(); System.out.println("Done! Here are the values we just read:"); for (int i = 0; i < scores.length; i++) { System.out.print(scores[i] + " "); } System.out.println(); } catch (IOException e) { System.out.println("I/O ERROR: Something went wrong with the " + "creation of the file of ints,\nbut because " + "some lazy programmer dumped all of the file " + "code into\none try block, I can't be more " + "specific! Here's what I can tell you:"); System.out.println(" The Error: " + e.getClass().getName()); String mesg = e.getMessage(); if (mesg == null) { System.out.println("The message: None."); } else { System.out.println("The message: " + mesg); } System.out.println("The stack trace:"); e.printStackTrace(); } } }