在文件中存储大量对象的最佳方法是什么?

What is the best way to store a huge set of objects in a file?

我有一个应用程序,有时可以在 list 中添加 数十万 个对象(存储在内存中并导致内存不足)。

我想 serialize 文件中的对象,而不是将其添加到 list 然后在需要时反序列化 。但问题是这个列表被许多查询填充。我不想把它留在记忆中。相反,我想继续将对象附加到文件中。

然后在写入时我想从文件中读取它。最好的方法是什么?

考虑到您对提出的问题的回答, 您可以使用像 Jackson 这样的 Json 序列化程序。将数据转换为 Json 对象的列表并将其保存到文件中。

但是就像这里的其他人已经说过的, 不推荐。

您需要使用数据库。

我没有使用数据库。而是使用 File.createTempFile.

生成文件

示例代码如下:

public class SerializeJavaDemo {
    // Just to generate some random strings
    private static final String AB = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    private static SecureRandom rnd = new SecureRandom();

    public static void main(String[] args) {
        SerializeJavaDemo sd = new SerializeJavaDemo();
        String prefix = "test";
        String suffix = "temp";
        File directory = new File("serialize");

        // Serialize and then read    
        try {
            File file = File.createTempFile(prefix, suffix, directory);

            FileOutputStream fos = new FileOutputStream(file);
            ObjectOutputStream output = new ObjectOutputStream(fos);
            List<TestClass> list = sd.createListOfTestClasses();

            for (TestClass test : list) {
                output.writeObject(test);
            }

            output.close();
            fos.close();

            FileInputStream fis = new FileInputStream(file);
            ObjectInputStream ois = new ObjectInputStream(fis);
            Object obj = null;

            int count = 0;
            while (true) {
                try {
                    obj = ois.readObject();
                    if (obj == null) {
                        break;
                    }
                    if (obj instanceof TestClass) {
                        count++;
                        System.out.println(count + "." + ((TestClass) obj).toString());
                    }
                } catch (Exception e) {
                    break;
                }
            }
            ois.close();
            fis.close();
            file.deleteOnExit();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public List<TestClass> createListOfTestClasses() {
        List<TestClass> list = new ArrayList<>();

        for (int i = 0; i < 100; i++) {
            String name = randomString(10);
            Random r = new Random();
            Integer id = r.nextInt();
            TestClass test = new TestClass(id, name);
            list.add(test);
        }
        return list;
    }

    private String randomString(int len) {
        StringBuilder sb = new StringBuilder(len);
        for (int i = 0; i < len; i++)
            sb.append(AB.charAt(rnd.nextInt(AB.length())));
        return sb.toString();
    }
}

测试 class 看起来像:

public class TestClass implements Serializable {

    /**
     * Serializable id
     */
    private static final long serialVersionUID = 5574815106264956078L;

    private int id;
    private String name;

    TestClass(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() { return id; }

    public void setId(int id) { this.id = id; }

    public String getName() { return name; }

    public void setName(String name) { this.name = name; }

    @Override
    public String toString() {
        return "TestClass [id=" + id + ", name=" + name + "]";
    }
}