Java saves an object to a file. and reads an object from a file

  • 2020-05-19 04:46:00
  • OfStack

1. Save the object to a file

The Java language can only save the objects of the classes that implement the Serializable interface to a file using the following method:


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 obj1 parameter must implement the Serializable interface, otherwise an java.io.NotSerializableException exception will be thrown. In addition, if the object being written to is a container, such as List, Map, make sure that every element in the container implements the Serializable interface as well. For example, if you declare an Hashmap as follows and call the writeObjectToFile method, an exception will be thrown. But if it's Hashmap < String,String > No problem, because the String class already implements the Serializable interface. In addition, if it is a self-created class, if the inherited base class does not implement Serializable, then the class needs to implement Serializable, otherwise 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 HashMap<String,Object>();
    objMap.put("test", obj);
    writeObjectToFile(objMap);

2. Read objects from files

You can read objects from a file using the following method


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 can be converted according to the actual type of the object.


Related articles: