Java:将对象保存在文本文件中?有现成的解决方案吗?

标签 java object store flat-file

我想保存我在程序中生成的对象。重新启动后,应用程序应自动加载数组中的所有对象。我想把它们写在一个文件中并在重启后解析它们。还有其他比手工更聪明的可能性吗? 谢谢

最佳答案

是的,您正在寻找的概念称为序列化。 Sun here 有一个很好的教程.

这个想法是你想要持久化的类必须实现 Serializable 接口(interface)。之后,您使用 java.io.ObjectOutputStream.writeObject() 将对象写入文件并使用 java.io.ObjectInputStream.readObject() 将其读回。

您不能序列化所有内容,因为有些序列化没有意义,但您可以解决它们。这是关于它的引述:

The basic mechanism of Java serialization is simple to use, but there are some more things to know. As mentioned before, only objects marked Serializable can be persisted. The java.lang.Object class does not implement that interface. Therefore, not all the objects in Java can be persisted automatically. The good news is that most of them -- like AWT and Swing GUI components, strings, and arrays -- are serializable.

On the other hand, certain system-level classes such as Thread, OutputStream and its subclasses, and Socket are not serializable. Indeed, it would not make any sense if they were. For example, thread running in my JVM would be using my system's memory. Persisting it and trying to run it in your JVM would make no sense at all. Another important point about java.lang.Object not implementing the Serializable interface is that any class you create that extends only Object (and no other serializable classes) is not serializable unless you implement the interface yourself (as done with the previous example).

That situation presents a problem: what if we have a class that contains an instance of Thread? In that case, can we ever persist objects of that type? The answer is yes, as long as we tell the serialization mechanism our intentions by marking our class's Thread object as transient.

关于Java:将对象保存在文本文件中?有现成的解决方案吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/170554/

相关文章:

java - 不使用 appender 的 Log4J 记录器

java - 如何将子类传递到需要父类(super class)作为参数的方法中

java - 如何获取我的 2 个对象并调用通过它传递变量的函数?

c# - 如何在c#中动态设置数组长度

google-play - 您必须让我们知道您的应用是 COVID-19 联系人追踪应用还是 Play 商店应用中的状态应用

mysql - 如何将超过 10 mb 的视频存储到 MySql 数据库中?

ruby-on-rails - 没有路由匹配 [GET] "/logout"

java - 如何使 JDBC 驱动程序在 Java 5 和 6 中工作?

java - Eclipse stdin 不发送回车和换行

qt - 如何指示 Qt Creator PRO 文件在单独的文件夹中输出 *.o 文件和 moc_* 文件?