无法从文件中读取对象并将它们放在java中的linkedlist中

时间:2015-01-03 15:54:04

标签: java file

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

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

写作方法如下所示

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

1 个答案:

答案 0 :(得分:1)

课程班正在实施java.io.Serializable
当您使用 ObjectInputStream 从文件中读取对象时,它应与您之前使用ObjectOutputStream存储它的顺序相同。并使用相同的对象类型。

如果您尝试阅读:

 (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;
}