简体   繁体   中英

how to use buffer to read and write java objects

I need to write and read objects to file. How i can do it with use of buffer? When i use it like that it's only write the last object to the file.

        OutputStream file = new FileOutputStream(DRB );
        OutputStream buffer = new BufferedOutputStream( file );
        ObjectOutput out = new ObjectOutputStream( buffer );

        try{
            out.writeObject(e1);
          }
          finally
          {
            buffer.flush();
            out.close();
          }

To append to an ObjectOutputStream there is only two options as I see it

  • read all the data into a list, add the item and write all the objects. An ObjectStream is a single continous stream. It is not like text where you can keep adding to the end.
  • use your own format to write multiple independent stream to the same file. You can write to a ByteArrayOutputStream, and use this to write the length of the stream before writing the contents. This way you can read the individual stream back in. I would only do this if you are confident in processing binary files.

The object you used e1 must be serialized class.

That's the only criteria.

You can have List of objects you want to write. Then, you can write this list.

Please see the code give below. Hope this will solve your problem:

package com.shineed.io;

import java.io.FileInputStream;

import java.io.ObjectInputStream;

import java.io.Serializable;

public class Deserializer{

   public static void main (String args[]) {

       Deserializer deserializer = new Deserializer();

       Customer customer = deserializer.deserialzeCustomer();

       System.out.println(customer);
   }

   public Customer deserialzeCustomer(){

       Customer customer;

       try{

           FileInputStream fin = new FileInputStream("c:\\customer.txt");
           ObjectInputStream ois = new ObjectInputStream(fin);
           customer = (Customer) ois.readObject();
           ois.close();

           return customer;

       }catch(Exception e){
           e.printStackTrace();
           return null;
       } 
   } 
}

Also see the Customer class given below:

package com.shineed.io;

import java.io.Serializable;

public class Customer implements Serializable {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    private String name;
    private String adress;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAdress() {
        return adress;
    }
    public void setAdress(String adress) {
        this.adress = adress;
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM