1

我有一个 Book 类和一个扩展 Book 的 Library Book 类。我将信息存储在随机访问文件中。我有一个 writeToFile 方法,它将 Book 对象写入随机访问文件。我的 LibraryBook 类的 writeToFile 方法调用 super.writeToFile,然后我希望它将特定于 LibraryBook 的字段写入文件。这样做的正确方法是什么?见代码:

book 类的方法:

public void writeToFile(String fileName, long location) throws Exception {
    try {
        RandomAccessFile invFile = new RandomAccessFile(fileName, "rw");
        // seek to correct record in file
        invFile.seek(location);
        // now write out the record
        // write out the data in fixed length fields
        // String fields must be truncated if too large
        // or padded with blanks if too small
                       //write out all Book variable to file
        invFile.writeLong(ISBN);
        //etc.....          

    } catch (FileNotFoundException notFound) {
        throw new FileNotFoundException();
    } catch (IOException io) {
        throw io;
    }
}

扩展 Book 的 LibraryBook 类中的方法:

    public void writeToFile(String fileName, long location) throws Exception {
    try {
        super.writeToFile(fileName, location);
        RandomAccessFile invFile = new RandomAccessFile(fileName, "rw");

        // seek to correct record in file
        invFile.seek(location);
        // now write out the record
        // write out the data in fixed length fields
        // String fields must be truncated if too large
        // or padded with blanks if too small
                       //write library book variables to file
        invFile.writeLong(branchID);
                        //etc....

                    invFile.close();
    } catch (FileNotFoundException notFound) {
        throw new FileNotFoundException();
    } catch (IOException io) {
        throw io;
    }
}

如何对其进行编码,以便 LibraryBook writeToFile 方法可以调用超类方法并将 LibraryBook 保存到文件中?

4

2 回答 2

0

您所做的实际上是将记录存储到文件中;已经有许多机制可用于将结构化数据存储到文件中。如果您有兴趣这样做是为了学习,那么一定要继续 - 但如果您只是想解决这个问题,请考虑使用SQLite3 之类的东西来为您提供存储。

如果您想继续使用这种方法,您需要确定每个方法将使用多少大小,将文件的一部分分配给每个要更新的方法,并确保每个方法都知道文件中的确切位置它的位置。

如果这只是一个 C 程序,我建议计算每个方法负责的字段、#define这些大小和#define要为每个方法添加的偏移量location

但这感觉不是很“Java”——您应该能够修改父母、孩子或完全添加新类,而无需了解其他类的详细信息。

因此,您可能希望让一个类负责将结构化数据写入文件并查询所涉及的每个类以获取其数据。让每个班级返回一个byte他们想要写入的 s 数组——并让一个大师班执行所有的写作。

通过将所有文件 IO 整合到一个类中,您可以在以后更轻松地更改为另一种存储格式,或者保持与您的程序的两个或三个先前版本的兼容性,或者提供多个数据库后端以满足部署时的不同需求。

于 2011-11-24T01:35:56.770 回答
0

使你的writeToFile()方法最终。

然后添加一个受保护的writeExtraData()方法,它在书的情况下什么都不做,但被覆盖以在LibraryBook类中写入额外的字段。从writeToFile()方法的中间调用它Book。您显然需要实现一组对称的读取方法。

更好的是,停止重新发明轮子和编写讨厌的样板代码,而只需使用语言提供的内置ObjectOutputStreamObjectInputStream类来完成这类事情。然后你就可以走了readObject()

于 2011-11-24T01:36:38.650 回答