// File Demo // (c) 1999 Andrea Danyluk import java.io.*; // need this in order to do file io. public class FileDemo { // pre: fileName is a valid file name // post: writes the integers 0 - 20 to a file public static void writeToFile(String fileName) throws IOException { DataOutputStream outFile = new DataOutputStream(new FileOutputStream(fileName)); for (int i = 0; i <= 20; i++) outFile.writeInt(i); outFile.writeInt(-100); // mark the end of the file outFile.close(); } // pre: filename is a valid file name // post: returns a vector containing numbers read from the file public static int[] readFromFile(String fileName) throws IOException { int[] numbers = new int[21]; int temp = 0; int index = 0; DataInputStream inFile = new DataInputStream(new FileInputStream(fileName)); temp = inFile.readInt(); while (temp != -100) { numbers[index] = temp; index++; temp = inFile.readInt(); } inFile.close(); return numbers; } public static void main(String args[]) { System.out.println( "Here we go..." ); String myFileName = "NumbersFile"; try // all file operations must be within "try" { writeToFile(myFileName); } catch(IOException e) // error with file operation { System.out.println("File error on output!\n"+ e.toString()); } try { int[] someNumbers = readFromFile("bob"); for (int i = 0; i < someNumbers.length; i++) System.out.println(someNumbers[i]); } catch (FileNotFoundException e) { System.out.println("File not found for read."); } catch(IOException e) // generic error with file operation { System.out.println("File error on input!\n"+ e.toString()); } System.out.println("But we can still go on!"); } }