简体   繁体   English

如何将文件中的多个对象读取到arraylist?

[英]How to read multiple objects in a file to an arraylist?

I'm trying to read all objects from a file and saving it to and array. 我正在尝试从文件中读取所有对象,并将其保存到and数组。 But, I get a StreamCorruptedException. 但是,我得到一个StreamCorruptedException。 Another question: it is unrelated : Whenever I view the file with objects stored in it, it's in Object language. 另一个问题:它不相关:每当我查看文件中存储的对象时,它都是使用对象语言。 Is it possible to turn it to human readable language? 可以将其转换为人类可读的语言吗?

public void generateLibReport() throws IOException, FileNotFoundException, ClassNotFoundException{

    ObjectInputStream ois = new ObjectInputStream(new 
    FileInputStream("LibrarianFile.txt"));
    boolean check = true;
    ArrayList<Librarian> array = new ArrayList();
    while(check){
        try{
            Librarian librarian = (Librarian)ois.readObject();
            array.add((Librarian)librarian);
        }
        catch(EOFException e){
            for(Librarian l:array){
            System.out.println(l);
            }
            check = false;
            ois.close();
        }
    }
}

If you want to use readable language, try save objects in JSON format. 如果要使用可读语言,请尝试以JSON格式保存对象。

For example use Gson library. 例如,使用Gson库。

void save(List<Librarian> libs) {
    String json = gson.toJson(libs);
    //save json text in simple text file
}

List<Librarian> load(String filename) {
    //read text file to json variable
    String json = ...;
    return gson.fromJson(json, new TypeToken<List<Librarian>>(){});
}

This way solve both questions. 这样可以解决两个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从文本文件中读取多个对象,然后发送到 ArrayList? - How to read multiple objects from a text file and then send to an ArrayList? Java将文件读入对象的数组列表并返回该数组列表 - Java read a file into an arraylist of objects and return that arraylist 如何在文件中读写对象的数组列表的数组列表? - How do I Read/Write an ArrayList of Arraylists of Objects to/from a file? 如何从二进制文件中的对象读取到Java中的ArrayList? - How to read objects from binary file to ArrayList in java? 从文件读取和写入对象的ArrayList的问题 - Problems with read and write an ArrayList of Objects from a file Java从文件中读取内容到ArrayList(对象) - Java read contents from file into ArrayList (Objects) 使用ObjectInputStream从文件中读取许多ArrayList对象吗? - Read many ArrayList Objects out of File with ObjectInputStream? 如何在一个文件中写入多个LinkList并将LinkedList读入LinkedList的ArrayList中? - How to write multiple LinkLists in a file and read the LinkedLists into a ArrayList of LinkedList? 如何使用扫描仪将多个数据类型文件读取到ArrayList中 - How to read multiple data type file into ArrayList using Scanner 如何使用 Jackson 读取 JSON 文件中的多个对象? - How to read multiple objects in a JSON file with Jackson?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM