1. Save the object to the file
The Java language can only save objects for classes that implement the serializable interface to a file, using 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 ();
}
Parameter obj must implement the Serializable interface, otherwise it throws a Java.io.NotSerializableException exception. In addition, if the object being written is a container, such as list, MAP, also ensure that each element in the container implements the serializable interface. For example, if you declare a hashmap as follows and call the Writeobjecttofile method, an exception is thrown. But if it is hashmap<string,string>, it will not go wrong because the String class has implemented the serializable interface. In addition, if the inherited base class does not implement serializable if it is a class created by itself, the class needs to implement serializable, or it cannot be written to the file in this way.
Object Obj=new object ();
Failed,the object in map does not implement Serializable interface hashmap<string
, object> objmap=new <String,Object> ();
Objmap.put ("Test", obj);
Writeobjecttofile (OBJMAP);
2. Reading objects from files
You can read objects from a file using the following methods
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 the object is read, it is converted based on the actual type of the object.
Above this Java to save the object to the file/read the object from the file is a small series to share all the content, I hope to give you a reference, but also hope that we support the cloud habitat community.