1. Save the object to the file
The Java language can only save objects of classes that implement the Serializable interface to a file, and use the following methods:
public static void writeObjectToFile(Object obj) { File file =new File("test.dat"); FileOutputStream out; try { out = new FileOutputStream(file); ObjectOutputStream objOut=new ObjectOutputStream(out); objOut.writeObject(obj); objOut.flush(); objOut.close(); System.out.println("write object success!"); } catch (IOException e) { System.out.println("write object failed"); e.printStackTrace(); } }The parameter obj must implement the Serializable interface, otherwise a java.io.NotSerializableException will be thrown. In addition, if the object written is a container, such as List or Map, it is also necessary to 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. But if it is Hashmap<String,String>, there will be no problem, because the String class has implemented the Serializable interface. In addition, if it is a class created by yourself, if the inherited base class does not implement Serializable, then the class needs to implement Serializable, otherwise it cannot be written to the file through this method.
Object obj=new Object(); //failed,the object in map does not implement Serializable interface HashMap<String, Object> objMap=new HashMap<String,Object>(); objMap.put("test", obj); writeObjectToFile(objMap);2. Read objects from the file
You can use the following method to read objects from a file
public static Object readObjectFromFile() { Object temp=null; File file =new File("test.dat"); FileInputStream in; try { in = new FileInputStream(file); ObjectInputStream objIn=new ObjectInputStream(in); temp=objIn.readObject(); objIn.close(); System.out.println("read object success!"); } catch (IOException e) { System.out.println("read object failed"); e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return temp; }After reading the object, convert it according to the actual type of the object.
The above article Java saves objects to/reads objects from files is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.