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
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.