Some things:
When you enter 1 to "write Data operation", you don't have a
break;
in your case statement, thus when you try to write the data, the integers gets written into the file, then the second case gets executed and you try to read from it. Not sure if this is your intention. But you can add abreak
to keep that from happening: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(); break;
When you try to read from your data file, you loop indefinitely:
while (true){ System.out.print(dInput.readInt()); }
That means it'll keep attempting to read serialized integers until the end of the file is reached. And when the end of the file has been reached, the stream throws an EOFException`. You can try changing your loop to this to prevent the exception:
while (dInput.available()>0){ System.out.print(dInput.readInt()); } break;
When you print the integers, they're going to be all jumbled up.
The text file is gibberish because it's not text. When you use a
DataOutputStream
the objects (or primitives) that you write into the stream gets processed so that the data is portable.