Java method for saving / reading objects to / from files

1. Save object to file

The Java language can only save the objects of classes that implement the serializable interface to a file by using the following methods:

The parameter obj must implement the serializable interface, otherwise Java. Obj will be thrown io. Notserializableexception exception. In addition, if the written object is a container, such as list and map, ensure that each element in the container also implements the serializable interface. For example, if you declare a HashMap as follows and call the writeobjecttofile method, an exception will be thrown. However, if HashMap < string, string > will not be a problem, because the string class has implemented the serializable interface. In addition, if it is a self created class, if the inherited base class does not implement serializable, the class needs to implement serializable, otherwise it cannot be written to the file through this method.

2. Read object from file

You can use the following methods to read objects from files

After the object is read, it can be converted according to the actual type of the object.

The above method of saving objects to / reading objects from files in Java is all the content shared by Xiaobian. I hope it can give you a reference and support more programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>