How to write and read java serialized objects into a file

前端 未结 5 1910
既然无缘
既然无缘 2020-11-27 03:13

I am going to write multiple objects to a file and then retrieve them in another part of my code. My code has no error, but it is not working properly. Could you please help

5条回答
  •  难免孤独
    2020-11-27 03:48

    Simple program to write objects to file and read objects from file.

    package program;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.io.Serializable;
    
    public class TempList {
    
      public static void main(String[] args) throws Exception {
        Counter counter = new Counter(10);
    
        File f = new File("MyFile.txt");
        FileOutputStream fos = new FileOutputStream(f);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(counter);
        oos.close();
    
        FileInputStream fis = new FileInputStream(f);
        ObjectInputStream ois = new ObjectInputStream(fis);
        Counter newCounter = (Counter) ois.readObject();
        System.out.println(newCounter.count);
        ois.close();
      }
    
    }
    
    class Counter implements Serializable {
    
      private static final long serialVersionUID = -628789568975888036 L;
    
      int count;
    
      Counter(int count) {
        this.count = count;
      }
    }

    After running the program the output in your console window will be 10 and you can find the file inside Test folder by clicking on the icon show in below image.

提交回复
热议问题