Tuesday, October 19, 2010

snippet : writing-objects-to-file-with-objectoutputstream

ObjectOutputStream outputStream = null;

try {

//Construct the LineNumberReader object
outputStream = new ObjectOutputStream(new FileOutputStream(filename));

Person person = new Person();
person.setFirstName("James");
person.setLastName("Ryan");
person.setAge(19);

outputStream.writeObject(person);

person = new Person();

person.setFirstName("Obi-wan");
person.setLastName("Kenobi");
person.setAge(30);

outputStream.writeObject(person);


} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
//Close the ObjectOutputStream
try {
if (outputStream != null) {
outputStream.flush();
outputStream.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}

No comments :

// Below script tag for SyntaxHighLighter