简体   繁体   中英

Reading objects from a .dat file using Java

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]);
    }
}      

Your problem is here:

Fraction[] updatedFractions = (Fraction[]) (input.readObject());

input.readObject() returns Fraction , but you are trying to cast it to Fraction[] , which is not a compatible type. You could read multiple Fraction s into an array to achieve the same result, though. You could use an ArrayList to do so, like this:

ArrayList<Fraction> fractions = new ArrayList<>();

try (
    ObjectInputStream input = new ObjectInputStream(new FileInputStream("SerialF.dat"))
) {
    while (input.available() > 0) {
        fractions.add((Fraction) input.readObject);
        
    }
}

Fraction[] updatedFractions = fractions.toArray(new Fraction[0]);

for (Fraction fraction : updatedFractions) {
    System.out.println(fraction);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM