使用ObjectInputStream时遇到问题,返回错误的值

时间:2015-01-09 20:04:43

标签: java

我有这个错误:

Exception in thread "main" java.lang.ClassCastException: java.util.ArrayList cannot be cast to domein.Auto

我得到的价值是:

[[nummerplaat= 123xyz, merk= Toyota, model = Yaris, nummerplaat= 456abc, merk= Opel, model = Astra, nummerplaat= azerty, merk= BMW, model = Berline, nummerplaat= qwerty, merk= Toyota, model = Avensis, nummerplaat= 789cde, merk= Mercedes, model = C-klasse Berline, nummerplaat= 567xyz, merk= Renault, model = Fluence, nummerplaat= ab12ab, merk= Opel, model = Zafira, nummerplaat= xy12xy, merk= Peugeot, model = 308]]

然而,这应该是:

[nummerplaat= 123xyz, merk= Toyota, model = Yaris, nummerplaat= 456abc, merk= Opel, model = Astra, nummerplaat= azerty, merk= BMW, model = Berline, nummerplaat= qwerty, merk= Toyota, model = Avensis, nummerplaat= 789cde, merk= Mercedes, model = C-klasse Berline, nummerplaat= 567xyz, merk= Renault, model = Fluence, nummerplaat= ab12ab, merk= Opel, model = Zafira, nummerplaat= xy12xy, merk= Peugeot, model = 308]

我正在使用的代码如下:

public class ObjectStreamManipulaties {

    public <E> List<E> geefObjecten(File naamBestand) {
        List<E> li = new ArrayList<>();

        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(naamBestand))) {
            while (true) {
                li.add((E) ois.readObject());
            }
        } catch (EOFException e) {
//EOF bereikt, continue
            return li;
        } catch (IOException | ClassNotFoundException ex) {
            Logger.getLogger(ObjectStreamManipulaties.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }
}

我在以下映射器类中使用此方法:

package persistentie;

import java.util.ArrayList;
import java.util.List;

import domein.Auto;
import java.io.File;

public class AutoMapper {

    private File naamBestand;

    public AutoMapper(File bestand){
        this.naamBestand = bestand;
    }

    public List<Auto> geefAutos() {

        System.out.println(new ObjectStreamManipulaties().geefObjecten(naamBestand));
        return new ObjectStreamManipulaties().geefObjecten(naamBestand);
    }
}

如果我像这样手动输入列表,一切正常:

public List<Auto> geefAutos() {
      List<Auto> lijstAutos = new ArrayList<Auto>();
      lijstAutos.add(new Auto("123xyz", "Toyota", "Yaris"));
      lijstAutos.add(new Auto("456abc", "Opel", "Astra"));
      lijstAutos.add(new Auto("azerty", "BMW", "Berline"));
      lijstAutos.add(new Auto("qwerty", "Toyota", "Avensis"));
      lijstAutos.add(new Auto("789cde", "Mercedes", "C-klasse Berline"));
      lijstAutos.add(new Auto("567xyz", "Renault", "Fluence"));
      lijstAutos.add(new Auto("ab12ab", "Opel", "Zafira"));
      lijstAutos.add(new Auto("xy12xy", "Peugeot", "308"));
      return lijstAutos;

    }

“li”的值是错误的。代码有什么问题?

2 个答案:

答案 0 :(得分:1)

您似乎正在从您的文件中读取整个列表,但假设其中包含单个元素。 不要执行while(true)循环,只需执行li = (List<E>) ois.readObject();

即可

答案 1 :(得分:0)

没有输出(当您保存文件时)代码我无法帮助您;然而,尝试输入/输出整个列表对象而不是逐个元素保存,更简单。