-1

Considering I have an object from a custom class and I write it to a .dat file using FileOutputStream and ObjectOutputStream . How will I modify a object present in the file? I can only read or write objects into a file.. I know that we can create a temporary file and then renaming the file accordingly, but isnt there any other way?

I do get outputs as expected , but isnt there any other method?

1 Answers1

0

Yes you can do it by using FileOutputStream & ObjectOutputStream class

 class MyBean {
   public String firstvalue;
   public String secondvalue;
   public MyBean (String firstvalue,String secondvalue){
     this.firstvalue=firstvalue;
     this.secondvalue=secondvalue;
  }

}
public class FileSerialization {

    public static void main(String[] args) {

        try {
            MyBean mb = new MyBean("first value", "second value");

            // write object to file
            FileOutputStream fos = new FileOutputStream("mybean.dat");
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(mb);
            oos.close();

            // read object from file
            FileInputStream fis = new FileInputStream("mybean.dat");
            ObjectInputStream ois = new ObjectInputStream(fis);
            MyBean result = (MyBean) ois.readObject();
            ois.close();

            System.out.println("One:" + result.firstvalue + ", Two:" + result.secondvalue);
          result.firstvalue="Changed;";

          // write object to file
            fos = new FileOutputStream("mybean.dat");
            oos = new ObjectOutputStream(fos);
            oos.writeObject(result);
            oos.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

}
Negi Rox
  • 3,828
  • 1
  • 11
  • 18
  • Thank you, but this code is used to read and write objects as such, right? What if I wanted to modify , for example, an object of MyBean present within the file? Sure, i can seek to it, but are we able to modify it? – Abhinand Hari Oct 18 '19 at 04:22
  • @AbhinandHari yes you can modify it and again you can save it in file. – Negi Rox Oct 18 '19 at 07:41