无法从文件中读取对象并将其放置到Java中的链表 [英] Can't read objects from file and place them to linkedlist in java

查看:32
本文介绍了无法从文件中读取对象并将其放置到Java中的链表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从文件中读取对象并将数据放置到 LinkedList 中,并返回对其的引用.但是当我尝试这种方法时,它会返回没有数据的LinkedList.

I want to read object from a file and place data to a LinkedList and return the reference to it. But when I try this method it returns LinkedList that have no data.

private static LinkedList<Course> readFromFile(String fileName)
        throws FileNotFoundException, IOException {
    LinkedList<Course> tmp = new LinkedList<Course>();

    reader = new ObjectInputStream(new FileInputStream(fileName));

    try {
        LinkedList<Course> readObject2 = (LinkedList<Course>) reader
                .readObject();
        LinkedList<Course> readObject = readObject2;
        tmp = readObject;
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

    return tmp;
}

我的写作方法是这样的

private static boolean writeToFile(String fileName, LinkedList<Course> templist)
        throws IOException {
    LinkedList<Course> templist1 = new LinkedList<Course>();

    if (createFile(fileName)) {
        FileOutputStream outF = new FileOutputStream(fileName);

        outO = new ObjectOutputStream(outF);
        outO.writeObject(templist1);

        //outO.flush();
        return true;
    }
    else
        return false;
}


书写方法如下


Writing method looks like this

private static boolean writeToFile(String fileName, LinkedList<Course> templist) throws IOException {
    LinkedList<Course> templist1 = new LinkedList<Course>();

    if (createFile(fileName)) {
        FileOutputStream outF = new FileOutputStream(fileName);

        outO = new ObjectOutputStream(outF);
        outO.writeObject(templist1);

        //outO.flush();
        return true;
    }
    else
        return false;
}

推荐答案

Course类正在实现

The Course class is implementing java.io.Serializable ?
When you read objects from a file with ObjectInputStream it should be in the same order that you stored it with ObjectOutputStream before. And with the same objects types.

如果您尝试阅读:

 (LinkedList<Course>) reader.readObject();

您必须将其存储为:

ObjectOutputStream writer = new ObjectOutputStream(
        new FileOutputStream(fileName));

writer.writeObject(yourLinkedListToSave);

如代码所示:

private static boolean writeToFile(String fileName, LinkedList<Course> templist) throws IOException {
    // Dont forget to initialize with your list else the list still empty
    LinkedList<Course> templist1 = new LinkedList<Course>(templist);

    if (createFile(fileName)) {
        FileOutputStream outF = new FileOutputStream(fileName);

        outO = new ObjectOutputStream(outF);
        outO.writeObject(templist1);

        //outO.flush();
        return true;
    }
    else
        return false;
}

这篇关于无法从文件中读取对象并将其放置到Java中的链表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆