I wrote up this class based on some examples I found online for Data Streams and I'm getting an EOFException at the end of each run. When I looked it up it said the end of the stream had been reached unexpectedly. It does appear to work on the console (at least it spits out the correct sequence of numbers). The text file is just gibberish though when I inspect the contents after running.
public class DataStreamExample {
public static void main(String args[]) {
int choice = 0;
int[] numbers = { 25, 4, 19, 70, 12, 28, 39, 30 };
System.out.println("This program will provide an example on how the Data Stream works.");
System.out.println("Note: Data Streams only work with primative data types.");
System.out.println();
System.out.println();
try {
System.out.println("1. For write Data operation");
System.out.println("2. For read Data operation");
System.out.println("Enter the number for the operation of your choice: ");
BufferedReader buffRead = new BufferedReader(new InputStreamReader(System.in));
choice = Integer.parseInt(buffRead.readLine());
switch(choice){
case 1:
FileOutputStream fileOut = new FileOutputStream("Example.txt");
BufferedOutputStream buffOut = new BufferedOutputStream(fileOut);
DataOutputStream dOutput =new DataOutputStream (buffOut);
for (int i = 0; i < numbers.length; i ++) {
dOutput.writeInt(numbers[i]);
}
System.out.print("writing data ");
dOutput.close();
case 2:
FileInputStream fileIn = new FileInputStream("Example.txt");
BufferedInputStream buffIn = new BufferedInputStream(fileIn);
DataInputStream dInput = new DataInputStream (buffIn);
while (true){
System.out.print(dInput.readInt());
}
default:
System.out.println("Invalid choice");
}
}
catch (Exception e) {
System.err.println("Error in read/write data to a file: " + e);
}
}
}
Does anyone have any advice or observations that can help clean this up so I don't get gibberish in the file and so it doesn't catch the exception? How should I be ending the operation and closing the stream?