I have 3 objects of type Fraction in a .dat file and I'm trying to read the contents of the .dat file using Java.
With the following block of code below, I keep getting a:
Exception in thread "main" java.lang.ClassCastException: class Fraction cannot be cast to class [LFraction; (Fraction and [LFraction; are in unnamed module of loader 'app')
at Mod8Problem1.main(Mod8Problem1.java:26)
I've tried a few things but I keep getting the same exception. What would be the best way to fix this?
try(
ObjectInputStream input = new ObjectInputStream(new FileInputStream("SerialF.dat"))
) {
Fraction[] updatedFractions = (Fraction[]) (input.readObject());
for (int i = 0; i < updatedFractions.length; i++) {
System.out.println(updatedFractions[i]);
}
}
Fraction, but the variable you use to reference it is aFraction[]. You'll need to loop an read eachFractionobject individually;readObject()is returning aFraction, not aFraction[].array.datwas serialized as an array. Arrays are objects, and can be serialized. However,SerialFis not a serialized array. Writing multiple objects to the same file is not the same as serializing an array. Sounds likeSerialFserialized multiple objects to the same file, whilearraysimply serialized an array (one object).Collectionor an array, in other words a single object that contains several, other objects. How was file SerialF.dat created?