*My assignment is to write a program that stores an array of five int values 1,2,3,4, and 5, a Date object for current time, and a double value 5.5. into a file named Exercies19_2.txt. Next, I am to write a method in the program that opens Exercises19_2.txt, reads the data and displays to the command window. When I run my program I keep getting this:
Exception in thread "main" java.io.OptionalDataException at java.io.ObjectInputStream.readObject0(Unknown Source) at java.io.ObjectInputStream.readObject(Unknown Source) at WriteArray.main(WriteArray.java:29).
Can you help me figure out what I am doing wrong????? Here is what I have written:
import java.io.*;
public class WriteArray {
public static void main(String[] args)throws ClassNotFoundException,IOException {
int[] numbers = {1, 2, 3, 4, 5};
//Create an output stream for file
ObjectOutputStream output = new ObjectOutputStream
(new FileOutputStream("Exercises19_2.txt", true));
//Write to file
output.writeDouble(5.5);
output.writeObject(numbers);
output.writeObject(new java.util.Date());
output.writeUTF("Exercises19_2.txt");
//Close the stream
output.close();
//Create an input stream for file
ObjectInputStream input = new ObjectInputStream
(new FileInputStream("Exercises19_2.txt"));
int[]newNumbers = (int[])(input.readObject());
for (int i = 0; i < newNumbers.length; i++)
System.out.println("Integers: " + newNumbers[i] + " ");
String FileName= input.readUTF();
double Double = input.readDouble();
java.util.Date date = (java.util.Date)(input.readObject());
System.out.println("DateTime: " + date);
//Display the output
System.out.println("Double: " + " " + input.readDouble());
System.out.println("FileName: " + " " + input.readUTF());
//Close the stream
input.close();
}
}