// File: MakeBinaryNSum.java // Input integers (unknown number on each line) from a text file. // Write each integer read into a binary file, open the binary file and // sum all values // Here the file input is done by wrapping a DataInputStreaFileInputStream with a // DataInputStream. This gives us the readLine method to permit // input of the file line by line // Also demonstrates catching an EOF exception import java.io.*; import java.util.*; public class MakeBinaryNSum { // Read a line from the input file and Sum the ints. // StringTokenizer allows each token on the line to be extracted. // Note that all tokens are strings and are then converted (see // the use of the Integer class to accomplish this) public static void ProcessLineToBinaryFile(String LineOfInts, DataOutputStream BinaryData) throws java.io.IOException {int Sum=0; StringTokenizer IntTokens=new StringTokenizer(LineOfInts); while (IntTokens.hasMoreTokens()) { BinaryData.writeInt(Integer.valueOf(IntTokens.nextToken()).intValue()); } } public static void ConvertToBinary(DataInputStream Input, DataOutputStream Output) throws java.io.IOException {String Line; while ((Line=Input.readLine())!=null) ProcessLineToBinaryFile(Line,Output); } public static void main(String[] args) throws java.io.IOException {int SumOfLine,SumOfFile=0; // Associate the disk file with the File object File InputFile=new File("int.dat"); // Now, open a stream from the input file DataInputStream DataInput= new DataInputStream(new FileInputStream(InputFile)); File BinaryFile=new File("int.bin"); DataOutputStream BinaryOutput= new DataOutputStream(new FileOutputStream(BinaryFile)); // Read the file and process it ConvertToBinary(DataInput,BinaryOutput); DataInput.close(); BinaryOutput.close(); DataInputStream BinaryInput=new DataInputStream(new FileInputStream(BinaryFile)); int Sum=0; try { while ((Sum+=BinaryInput.readInt())!=-1); } catch (java.io.EOFException EOF) {System.out.println("EOF reached"); } System.out.println("Sum is:"+Sum); } }