从文件写入/读取多个对象

时间:2019-12-05 06:33:37

标签: java arrays arraylist objectinputstream objectoutputstream

[EDIT]我有一个名为'Keys'的主类,它具有键的arrayList和一些方法。我可以将多个密钥写入文件并从文件中读取所有密钥。但是当我关闭程序并重新打开它时,由于某种原因该文件读取为空...这是一些代码 (按键类)(其中一些)

private static ArrayList<Key> keys = new ArrayList<Key>();


    public static void serialize(File file) throws IOException{
        FileOutputStream fi = new FileOutputStream(file);
        ObjectOutputStream oos = new ObjectOutputStream(fi);

        oos.writeObject(keys);
        oos.close();
    }

    @SuppressWarnings("unchecked")
    public static ArrayList<Key> deSerialize(File file) throws IOException, ClassNotFoundException{
        FileInputStream fi = new FileInputStream(file);
        ObjectInputStream ois = new ObjectInputStream(fi);

        keys = (ArrayList<Key>)ois.readObject();
        for (Key k : keys) {
            System.out.println("Got key: " + k.getName());
        }
        ois.close();
        return keys;
    }

这是即时通讯读取数据的方式(在其他类中)

if (!Keys.isNull()) {
                    ArrayList<Key> keys = Keys.deSerialize(keyFile);
                    for (int i = 0; i < keys.size(); i++) {
                        Keys.getKeyAt(i).getName();
                    }
                } else {
                    System.out.println("Keys are null");
                }

这就是我如何为其编写密钥

Keys.addKey(new Key(replace, replaceWith, IDtext));
                Keys.serialize(keyFile);

就像我说的那样,它将从文件中读取一个并且只有一个对象。我肯定我能弄清楚这一点,但是我喜欢这个网站并大量使用它,所以以为id成为了它的一部分并发布了。

0 个答案:

没有答案