/* Author : Michael Robinson Program : filesBinary.java Purpose : This program creates a binary files writes data to it closes file and then opens the binary file, reads and displays the contents. Updated : Jan 29, 2099 */ import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.EOFException; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class filesBinary { //create numbers.dat binary file if it does not exist public static void createBinaryFile( int numbers[] ) throws IOException { //accepted array to be written to a file: //int numbers[] = { 2, 4, 6, 8, 10, 12, 14 }; //create the binary outputBinary object //if file exists it appends data to it //else creates a new file, done by true parameter. FileOutputStream outputBinary = new FileOutputStream( "numbers.dat", true ); //creates the outputBinFile object to write data into //the numbers.dat binary file DataOutputStream outputBinFile = new DataOutputStream( outputBinary ); System.out.println( "Writing the numbers to the file..." ); //write the array elements into the numbers.dat binary file for( int i = 0; i < numbers.length; i++ ) { outputBinFile.writeInt( numbers[i] ); System.out.print( numbers[i] + " " ); } //outputBinFile.writeChars("\n"); System.out.println( "\nDone." ); //close the file. outputBinFile.close(); }//end public static void createBinaryFile() //opens and reads all records in numbers.dat binary file public static void openReadBinaryFile( int numbersLength ) throws IOException { int number = 0; //number read from the file boolean endOfFile = false; //EOF flag //Create the inputBinary object to help in reading the //numbers.dat binary file FileInputStream inputBinary = new FileInputStream( "numbers.dat" ); //Create the inputBFile object to be able to use the previous //inputBinary object to read the numbers.dat binary file DataInputStream inputBFile = new DataInputStream( inputBinary ); System.out.println( "\nReading numbers from Binary file:" ); //read and display all the records in the numbers.dat file. while( !endOfFile ) { try { for( int x = 0; x < numbersLength; x++ ) { number = inputBFile.readInt(); //read record System.out.printf( "%d ", number ); //display record } System.out.println(); } catch ( EOFException e ) { endOfFile = true; } }//end public static void openReadBinaryFile( int //numbersLength ) throws IOException System.out.println( "\nDone." ); //close the file inputBFile.close(); }//end public static void openReadBinaryFile() throws IOException public static void main( String args[] ) throws IOException { //create array to be written into numbers.dat binary file int numbers[] = { 2, 4, 6, 8, 10, 12, 14 }; //create numbers.dat binary file and write array data into it createBinaryFile( numbers ); //open, read and display all data in numbers.dat binary file openReadBinaryFile( numbers.length ); }//end public static void main(String[] args) throws IOException }//end public class filesBinary