代码之家  ›  专栏  ›  技术社区  ›  Michael

为什么我不能正确地从文件中获取对象?

  •  0
  • Michael  · 技术社区  · 7 年前

    我有一个自定义对象列表,我先编写然后读取到文件中。

    这是我的课:

    public class Book implements Serializable{
       private int isbn;
       private String category;
       private String authorName;
    
        public int getIsbn() {
            return isbn;
        }
    
        public String getCatId() {
            return category;
        }
    
    
        public void setIsbn(int isbn) {
            this.isbn = isbn;
        }
    
        public void setCategory(String category) {
            this.category = category;
        }
    
    
        public void setAuthorName(String authorName) {
            this.authorName = authorName;
        }
    
        public String getAuthorName() {
            return authorName;
        }
    
        public Book() {}
    
        //copy book 
        public Book(Book book, int id) {
            this.category = book.category;
            this.title = book.title;
            this.authorName = book.authorName;
            this.isbn = id;
        } 
    }
    

    下面是我用来编写对象列表的函数:

    private static <T> void writeToFile(List<T> items, String fileName) {
        try {
            String path = "src\\hw1\\library\\repos\\" + fileName;
    
            FileOutputStream f = new FileOutputStream(path, true);// true- means append to file
            ObjectOutputStream o = new ObjectOutputStream(f);
    
            // Write objects to file
            o.writeObject(items);
            o.close();
            f.close();
        } catch (Exception e) {}
    }
    

    下面是我从列表中读到的函数:

    private static <T> List<T> readFromFile(Context context, String fileName) {
        try {
             String path = "src\\hw1\\library\\repos\\" +fileName ;
    
             FileInputStream fi = new FileInputStream(path);
             ObjectInputStream oi = new ObjectInputStream(fi);
             // Read objects
             List<T> items = (List<T>)oi.readObject();
             oi.close();
             fi.close();
    
             return items;
        } catch (Exception e) {}
        return null;
    }
    

    对象列表被写入文件,

    知道为什么我从第一次写入文件的仅文件对象中获取吗?

    1 回复  |  直到 7 年前
        1
  •  0
  •   Antoniossss    7 年前

    我只知道

    但是当我试图用函数来读它时 仅从第一次写入文件的对象。

    单次写入将把给定的列表放入文件,第二次写入将 再列一张单子 因为你是 追加到文件

    现在,你读方法 总是从头读 所以每次调用 readFromFile 将导致从给定的文件中读取相同的(第一个)对象(按您的情况列出)。你得做更多 f.readObject() 在同一条河流上。

    如果您不打算一次读取所有对象,我建议每个列表使用一个文件,这样您就不会使用file seeking来“移动”文件指针的位置(也不会执行空操作 F.读取对象() 调用)