/* * T03n05.java -- Use DataOutputStream to create a binary file of ints * The ints will be read from the file in the next example program. * To write values of primitive types, the class DataOutputStream provides * appropriate methods. DataOutputStream builds on FileOutputStream, which * in turn builds on File. Here are (roughly) the reasons we need all three: * We need to associate with a physical file (File) * We need to have a way to write bytes to it (FileOutputStream) * We need to convert primitive type values into bytes (DataOutputStream) * * A note on exceptions: As I'll often do in these examples, I'm sacrificing * good programming practice in order to better focus on the topic at * hand. So, instead of properly try/catching the individual statements that * can throw an IOException, I'm just lumping the whole block of code into * one try block. At least this makes the file code clear. And, it gave me * an opportunity to use a finally{} block. :-) */ import java.io.*; public class T03n05 { public static void main (String [] args) { final String fileName = "T03n05.out"; File fileRef; FileOutputStream byteStream; DataOutputStream intStream = null; int[] scores = { 43, 56, 54, 63, 49, -2 }; System.out.println("Writing an array of ints to the file '" + fileName + "'..."); try { fileRef = new File(fileName); byteStream = new FileOutputStream(fileRef); intStream = new DataOutputStream(byteStream); for (int i = 0; i < scores.length; i++) { intStream.writeInt(scores[i]); } intStream.close(); } 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(); } finally { System.out.println("Done!"); } } }