ramnram
asked on
appeding objects in file using ObjectOutputStream
i tried to append objects but i couldn't.
can anyone help me to solve this problem.
i've given sample code below.
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("file1.tx t",true));
................
...............
oos.writeObject(address);/ /address is an instance of a class Address
can anyone help me to solve this problem.
i've given sample code below.
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("file1.tx
................
...............
oos.writeObject(address);/
Deserializing
try {
// Deserialize from a file
File file = new File("filename.ser");
ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
// Deserialize the object
javax.swing.JButton button = (javax.swing.JButton) in.readObject();
in.close();
// Get some byte array data
byte[] bytes = getBytesFromFile(file);
// see e36 Reading a File into a Byte Array for the implementation of this method
// Deserialize from a byte array
in = new ObjectInputStream(new ByteArrayInputStream(bytes ));
button = (javax.swing.JButton) in.readObject();
in.close();
} catch (ClassNotFoundException e) {
} catch (IOException e) {
}
try {
// Deserialize from a file
File file = new File("filename.ser");
ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
// Deserialize the object
javax.swing.JButton button = (javax.swing.JButton) in.readObject();
in.close();
// Get some byte array data
byte[] bytes = getBytesFromFile(file);
// see e36 Reading a File into a Byte Array for the implementation of this method
// Deserialize from a byte array
in = new ObjectInputStream(new ByteArrayInputStream(bytes
button = (javax.swing.JButton) in.readObject();
in.close();
} catch (ClassNotFoundException e) {
} catch (IOException e) {
}
class Address implements Serializable
{
...
...
,..
}
ObjectOutput out = new ObjectOutputStream(new FileOutputStream("filename .ser"));
out.writeObject(new Address());
-------------------------- ---------- ---------- -------
// Deserialize from a file
File file = new File("filename.ser");
ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
// Deserialize the object
Address address= (Address) in.readObject();
in.close();
{
...
...
,..
}
ObjectOutput out = new ObjectOutputStream(new FileOutputStream("filename
out.writeObject(new Address());
--------------------------
// Deserialize from a file
File file = new File("filename.ser");
ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
// Deserialize the object
Address address= (Address) in.readObject();
in.close();
>> i tried to append objects but i couldn't.
Your class should implement Serializable interface
Your class should implement Serializable interface
Try this, have tested it and make sure the class Address implements serializable.
Cheers!
package ee;
import java.io.*;
public class test {
public test(){}
public static void main(String args[])
{
try{
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("c:/file1 .txt",true ));
Address address=new Address();
oos.writeObject(address);/ /address is an instance of a class Address
}catch (IOException e){
System.out.println(e);
}
}
}
package ee;
import java.io.*;
public class Address implements Serializable{
public String test;
public Address(){
test="Test";
}
}
Cheers!
package ee;
import java.io.*;
public class test {
public test(){}
public static void main(String args[])
{
try{
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("c:/file1
Address address=new Address();
oos.writeObject(address);/
}catch (IOException e){
System.out.println(e);
}
}
}
package ee;
import java.io.*;
public class Address implements Serializable{
public String test;
public Address(){
test="Test";
}
}
ASKER
Thanx for ur response.
But how can i retrieve the objects that we wrote in to the file.
i got an exception "StreamCurruptedException" after reading the first record.
I have given the code below.
Run the code atleast twice. so that the file contains more than one record.
import java.io.*;
public class test {
public test(){}
public static void main(String args[])
{
try{
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("c:/file1 .txt",true ));
Address address=new Address();
oos.writeObject(address);/ /address is an instance of a class Address
}catch (IOException e){
System.out.println(e);
}
try{
ObjectInputStream oos = new ObjectInputStream(new FileInputStream("c:/file1. txt"));
while(true)
{
Address address=new Address();
address=(Address)oos.readO bject();// address is an instance of a class Address
System.out.println("\n " + address.test);
}
}catch (Exception e){ System.out.println(e); }
}
}
class Address implements Serializable{
public String test;
public Address(){
test="popopppopp";
}
}
But how can i retrieve the objects that we wrote in to the file.
i got an exception "StreamCurruptedException"
I have given the code below.
Run the code atleast twice. so that the file contains more than one record.
import java.io.*;
public class test {
public test(){}
public static void main(String args[])
{
try{
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("c:/file1
Address address=new Address();
oos.writeObject(address);/
}catch (IOException e){
System.out.println(e);
}
try{
ObjectInputStream oos = new ObjectInputStream(new FileInputStream("c:/file1.
while(true)
{
Address address=new Address();
address=(Address)oos.readO
System.out.println("\n " + address.test);
}
}catch (Exception e){ System.out.println(e); }
}
}
class Address implements Serializable{
public String test;
public Address(){
test="popopppopp";
}
}
If you save an object of Class A and after and object of class B, when you read you must take first the object of Class A and then the object of Class B. And both must be serializable.
In your case you must close the file before you read.
put
oos.flush();
oos.close();
before opening again the file.
oos.flush();
oos.close();
before opening again the file.
Guess your file file1.txt has contains when you run your script?
I tried your program and did not get the same problem as you mentioned.
Maybe just delete the file file1.txt and rerun your program to make sure your file is empty.
Should be ok. :)
I tried your program and did not get the same problem as you mentioned.
Maybe just delete the file file1.txt and rerun your program to make sure your file is empty.
Should be ok. :)
ASKER
My actual need is to store and read list of addresses to or from a file.
i've written program to do so that i've given below.
the problem is i unable to append and read back all records.it doesn't give
any compile or runtime errors.
public class Address implements Serializable
{
String name;
String phone;
String email;
public void set(String nAme,String Phone,String Email)
{
name=nAme;
phone=Phone;
email=Email;
}
public void display()
{
System.out.println("\n" + name +putChar(" ",25-name.length())+ phone + putChar(" ",15-phone.length())+ email +putChar(" ",15-email.length()));
}
private static String putChar(String chr,int no)//It returns a string of given char no of times
{ String s="";
for (int i=0;i<no ;i++ ){s=s+ chr;}
return s;
}
}
class AddressBook extends ArrayList
{
public void addAddress(ObjectOutputStr
{
Address address=new Address();
address.set(name,phone,ema
oos.writeObject(address);
}
public void loadAddress(ObjectInputStr
{
Address address;
boolean again=true;
while(again)
{ try
{
address=(Address)ois.readO
this.add(address);
}
catch(Exception e)
{ again=false;}
}
ois.close();
}
public void displayAddress()
{
for(int i=0;i<this.size();i++)
{
Address address =(Address)this.get(i);
address.display();
}
System.out.println("No of Records:" + this.size());
}
}
class AddBook
{
public static void main (String [] arguments)throws Exception
{
int option;
boolean again=true;
String temp;
BufferedReader input= new BufferedReader(new InputStreamReader(System.i
while(again)
{
System.out.println("\n\n ADDRESS BOOK");//Menu items to be displayed
System.out.println(" ------------");
System.out.println("\n 1. ADD");
System.out.println(" 2. LIST");
System.out.println(" 5. EXIT");
System.out.print("\n\n Enter your option: ");
temp=input.readLine();
option=(isNumeric(temp)?In
switch(option)
{
case 1: //To Add new contacts to Addres Book
readAddress();
break;
case 2: //To Display contacts in the Addres Book
displayAddress();
break;
case 5://To exit from the Addres Book
again=false;
break;
default://Other than option given
System.out.println("\n Invalid option.");
}
System.out.print("\n\n\n\n
temp=input.readLine();
}
}
static void displayAddress()throws Exception
{
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("C:/AddBoo
AddressBook aBook = new AddressBook ();
aBook.loadAddress(ois);
aBook.displayAddress();
ois.close();
}
static void readAddress()throws Exception
{
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("C:/AddBo
BufferedReader br= new BufferedReader(new InputStreamReader(System.i
AddressBook aBook = new AddressBook ();
String name,phone,email;
System.out.print("\nEnter name:");
name=br.readLine();
System.out.print("\nEnter phone:");
phone=br.readLine();
System.out.print("\nEnter email:");
email=br.readLine();
aBook.addAddress(oos,name,
oos.close();
}
static boolean isNumeric(String str)throws Exception
{
try
{ int t=Integer.parseInt(str);
return true;
}
catch(NumberFormatExceptio
}
}
put oos.flush();
aBook.addAddress(oos,name, phone,emai l);
oos.flush();<------------- --------in sert here.
oos.close();
aBook.addAddress(oos,name,
oos.flush();<-------------
oos.close();
ASKER
fredwangus,
I tried ur suggestion. but it made no difference.
This is wat i hav at the end of second execution of program.
------------->File1.txt<-- ---------- ----------
¬í sr Address¡wóðBÌê L testt Ljava/lang/String;xpt
popopppopp
¬í sr Address¡wóðBÌê L testt Ljava/lang/String;xpt dffdfdfff
-------------------->end of File1.txt<---------------- ----
U can see every record contains a header..(¬í sr Address¡wóðBÌê L testt Ljava/lang/String;xpt --> is a header)
i am using java1.4.2 version.
I tried ur suggestion. but it made no difference.
This is wat i hav at the end of second execution of program.
------------->File1.txt<--
¬í sr Address¡wóðBÌê L testt Ljava/lang/String;xpt
popopppopp
¬í sr Address¡wóðBÌê L testt Ljava/lang/String;xpt dffdfdfff
-------------------->end of File1.txt<----------------
U can see every record contains a header..(¬í sr Address¡wóðBÌê L testt Ljava/lang/String;xpt --> is a header)
i am using java1.4.2 version.
I created 3 files using your code and run AddBook, acturally your program is functioning properly.
Attached the code I used and see whether it works at your side or not:
package ee;
import java.io.*;
class AddBook
{
public static void main (String [] arguments)throws Exception
{
int option;
boolean again=true;
String temp;
BufferedReader input= new BufferedReader(new InputStreamReader(System.i n));
while(again)
{
System.out.println("\n\n ADDRESS BOOK");//Menu items to be displayed
System.out.println(" ------------");
System.out.println("\n 1. ADD");
System.out.println(" 2. LIST");
System.out.println(" 5. EXIT");
System.out.print("\n\n Enter your option: ");
temp=input.readLine();
option=(isNumeric(temp)?In teger.pars eInt(temp) :0);
switch(option)
{
case 1: //To Add new contacts to Addres Book
readAddress();
break;
case 2: //To Display contacts in the Addres Book
displayAddress();
break;
case 5://To exit from the Addres Book
again=false;
break;
default://Other than option given
System.out.println("\n Invalid option.");
}
System.out.print("\n\n\n\n Press enter to continue...");
temp=input.readLine();
}
}
static void displayAddress()throws Exception
{
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("C:/AddBoo k.txt"));
AddressBook aBook = new AddressBook ();
aBook.loadAddress(ois);
aBook.displayAddress();
ois.close();
}
static void readAddress()throws Exception
{
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("C:/AddBo ok.txt",tr ue));
BufferedReader br= new BufferedReader(new InputStreamReader(System.i n));
AddressBook aBook = new AddressBook ();
String name,phone,email;
System.out.print("\nEnter name:");
name=br.readLine();
System.out.print("\nEnter phone:");
phone=br.readLine();
System.out.print("\nEnter email:");
email=br.readLine();
aBook.addAddress(oos,name, phone,emai l);
oos.close();
}
static boolean isNumeric(String str)throws Exception
{
try
{ int t=Integer.parseInt(str);
return true;
}
catch(NumberFormatExceptio n e) {return false;}
}
}
/*
* Created on Oct 4, 2004
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package ee;
import java.io.*;
public class Address implements Serializable
{
String name;
String phone;
String email;
public void set(String nAme,String Phone,String Email)
{
name=nAme;
phone=Phone;
email=Email;
}
public void display()
{
System.out.println("\n" + name +putChar(" ",25-name.length())+ phone + putChar(" ",15-phone.length())+ email +putChar(" ",15-email.length()));
}
private static String putChar(String chr,int no)//It returns a string of given char no of times
{
String s="";
for (int i=0;i<no ;i++ ){s=s+ chr;}
return s;
}
}
package ee;
import java.io.*;
import java.util.*;
class AddressBook extends ArrayList
{
public void addAddress(ObjectOutputStr eam oos,String name,String phone,String email) throws Exception
{
Address address=new Address();
address.set(name,phone,ema il);
oos.writeObject(address);
}
public void loadAddress(ObjectInputStr eam ois) throws Exception
{
Address address;
boolean again=true;
while(again)
{ try
{
address=(Address)ois.readO bject();
this.add(address);
}
catch(Exception e)
{ again=false;}
}
ois.close();
}
public void displayAddress()
{
for(int i=0;i<this.size();i++)
{
Address address =(Address)this.get(i);
address.display();
}
System.out.println("No of Records:" + this.size());
}
}
Attached the code I used and see whether it works at your side or not:
package ee;
import java.io.*;
class AddBook
{
public static void main (String [] arguments)throws Exception
{
int option;
boolean again=true;
String temp;
BufferedReader input= new BufferedReader(new InputStreamReader(System.i
while(again)
{
System.out.println("\n\n ADDRESS BOOK");//Menu items to be displayed
System.out.println(" ------------");
System.out.println("\n 1. ADD");
System.out.println(" 2. LIST");
System.out.println(" 5. EXIT");
System.out.print("\n\n Enter your option: ");
temp=input.readLine();
option=(isNumeric(temp)?In
switch(option)
{
case 1: //To Add new contacts to Addres Book
readAddress();
break;
case 2: //To Display contacts in the Addres Book
displayAddress();
break;
case 5://To exit from the Addres Book
again=false;
break;
default://Other than option given
System.out.println("\n Invalid option.");
}
System.out.print("\n\n\n\n
temp=input.readLine();
}
}
static void displayAddress()throws Exception
{
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("C:/AddBoo
AddressBook aBook = new AddressBook ();
aBook.loadAddress(ois);
aBook.displayAddress();
ois.close();
}
static void readAddress()throws Exception
{
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("C:/AddBo
BufferedReader br= new BufferedReader(new InputStreamReader(System.i
AddressBook aBook = new AddressBook ();
String name,phone,email;
System.out.print("\nEnter name:");
name=br.readLine();
System.out.print("\nEnter phone:");
phone=br.readLine();
System.out.print("\nEnter email:");
email=br.readLine();
aBook.addAddress(oos,name,
oos.close();
}
static boolean isNumeric(String str)throws Exception
{
try
{ int t=Integer.parseInt(str);
return true;
}
catch(NumberFormatExceptio
}
}
/*
* Created on Oct 4, 2004
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package ee;
import java.io.*;
public class Address implements Serializable
{
String name;
String phone;
String email;
public void set(String nAme,String Phone,String Email)
{
name=nAme;
phone=Phone;
email=Email;
}
public void display()
{
System.out.println("\n" + name +putChar(" ",25-name.length())+ phone + putChar(" ",15-phone.length())+ email +putChar(" ",15-email.length()));
}
private static String putChar(String chr,int no)//It returns a string of given char no of times
{
String s="";
for (int i=0;i<no ;i++ ){s=s+ chr;}
return s;
}
}
package ee;
import java.io.*;
import java.util.*;
class AddressBook extends ArrayList
{
public void addAddress(ObjectOutputStr
{
Address address=new Address();
address.set(name,phone,ema
oos.writeObject(address);
}
public void loadAddress(ObjectInputStr
{
Address address;
boolean again=true;
while(again)
{ try
{
address=(Address)ois.readO
this.add(address);
}
catch(Exception e)
{ again=false;}
}
ois.close();
}
public void displayAddress()
{
for(int i=0;i<this.size();i++)
{
Address address =(Address)this.get(i);
address.display();
}
System.out.println("No of Records:" + this.size());
}
}
ASKER
hi giant2,
Thanks 4 ur suggestion. but still(after putting flush(); in that place) i'm getting the same problem.
Thanks 4 ur suggestion. but still(after putting flush(); in that place) i'm getting the same problem.
try this
import java.util.*;
import java.io.*;
public class test {
public test() {}
public static void main(String args[]) {
test tes = new test();
Object[] array = tes.deserialize();
tes.serialize(array, new Address());
}
public void serialize(Object[] array, Object object) {
try {
// Serialize to a file
ObjectOutput out = new ObjectOutputStream(new FileOutputStream(
"filename.ser", true));
for (int i = 0; i < array.length; i++) {
out.writeObject(array[i]);
}
out.writeObject(object);
out.flush();
out.close();
}
catch (Exception ex) {
}
}
public Object[] deserialize() {
File file = new File("filename.ser");
Vector vect = new Vector();
ObjectInputStream in = null;
try {
// Deserialize from a file
in = new ObjectInputStream(new FileInputStream(file));
// Deserialize the object
while (true) {
Address add = (Address) in.readObject();
if (add == null) {
break;
}
vect.add(add);
System.err.println(add.tes t);
}
in.close();
}
catch (Exception ex) {
System.err.println(ex);
}
return vect.toArray();
}
}
class Address
implements Serializable {
public String test;
public Address() {
test = "popopppopp";
}
}
import java.util.*;
import java.io.*;
public class test {
public test() {}
public static void main(String args[]) {
test tes = new test();
Object[] array = tes.deserialize();
tes.serialize(array, new Address());
}
public void serialize(Object[] array, Object object) {
try {
// Serialize to a file
ObjectOutput out = new ObjectOutputStream(new FileOutputStream(
"filename.ser", true));
for (int i = 0; i < array.length; i++) {
out.writeObject(array[i]);
}
out.writeObject(object);
out.flush();
out.close();
}
catch (Exception ex) {
}
}
public Object[] deserialize() {
File file = new File("filename.ser");
Vector vect = new Vector();
ObjectInputStream in = null;
try {
// Deserialize from a file
in = new ObjectInputStream(new FileInputStream(file));
// Deserialize the object
while (true) {
Address add = (Address) in.readObject();
if (add == null) {
break;
}
vect.add(add);
System.err.println(add.tes
}
in.close();
}
catch (Exception ex) {
System.err.println(ex);
}
return vect.toArray();
}
}
class Address
implements Serializable {
public String test;
public Address() {
test = "popopppopp";
}
}
Or try this
XMLEncoder e = new XMLEncoder(
new BufferedOutputStream(
new FileOutputStream("addresse s.xml",tru e)));
e.writeObject(new Address());
e.close();
XMLDecoder d = new XMLDecoder(
new BufferedInputStream(
new FileInputStream("doctors.x ml")));
Address add = (Address)d.readObject();
d.close();
XMLEncoder e = new XMLEncoder(
new BufferedOutputStream(
new FileOutputStream("addresse
e.writeObject(new Address());
e.close();
XMLDecoder d = new XMLDecoder(
new BufferedInputStream(
new FileInputStream("doctors.x
Address add = (Address)d.readObject();
d.close();
ASKER
fredwangus ,
did u try with option 2 (while excuting the program)to list out records and did u get all records from the file?
did u try with option 2 (while excuting the program)to list out records and did u get all records from the file?
import java.util.*;
import java.io.*;
import java.beans.*;
public class test {
public test() {}
public static void main(String args[]) {
test tes = new test();
tes.serialize(new Address());
}
public void serialize(Object object) {
try {
XMLEncoder e = new XMLEncoder(
new BufferedOutputStream(
new FileOutputStream("addresse s.xml", true)));
e.writeObject(new Address());
e.close();
}
catch (Exception ex) {
}
}
public void deserialize() {
try {
XMLDecoder d = new XMLDecoder(
new BufferedInputStream(
new FileInputStream("addresses .xml")));
while (true) {
Address add = (Address) d.readObject();
if (add == null) {
break;
}
}
d.close();
}
catch (Exception ex) {
System.err.println(ex);
}
}
}
class Address
implements Serializable {
public String test;
public Address() {
test = "popopppopp";
}
}
import java.io.*;
import java.beans.*;
public class test {
public test() {}
public static void main(String args[]) {
test tes = new test();
tes.serialize(new Address());
}
public void serialize(Object object) {
try {
XMLEncoder e = new XMLEncoder(
new BufferedOutputStream(
new FileOutputStream("addresse
e.writeObject(new Address());
e.close();
}
catch (Exception ex) {
}
}
public void deserialize() {
try {
XMLDecoder d = new XMLDecoder(
new BufferedInputStream(
new FileInputStream("addresses
while (true) {
Address add = (Address) d.readObject();
if (add == null) {
break;
}
}
d.close();
}
catch (Exception ex) {
System.err.println(ex);
}
}
}
class Address
implements Serializable {
public String test;
public Address() {
test = "popopppopp";
}
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
If you write the setters and getters to your class,
then this model is good for your requirement
public class Address
{
private String test;
public Address() {
}
public void setTest(String str)
{
test=str;
}
public String getTest()
{
return test;
}
}
import java.util.*;
import java.io.*;
import java.beans.*;
public class test {
public test() {}
public static void main(String args[]) {
test tes = new test();
Address array[]=tes.readObjects();
for(int i=0;i<array.length;i+=1)
{
tes.add(array[i]);
}
Address add=new Address();
add.setTest(args[0]);
tes.add(add);
}
public Address[] readObjects()
{
Vector vect=new Vector();
try {
XMLDecoder d = new XMLDecoder(
new BufferedInputStream(
new FileInputStream("addresses .xml")));
while (true) {
Address add = (Address) d.readObject();
if (add == null) {
break;
}
vect.add(add);
}
d.close();
}
catch (Exception ex) {
System.err.println(ex);
}
return (Address[])vect.toArray(ne w Address[0]);
}
public void add(Object object) {
try {
XMLEncoder e = new XMLEncoder(
new BufferedOutputStream(
new FileOutputStream("addresse s.xml", true)));
e.writeObject(new Address());
e.close();
}
catch (Exception ex) {
}
}
}
then this model is good for your requirement
public class Address
{
private String test;
public Address() {
}
public void setTest(String str)
{
test=str;
}
public String getTest()
{
return test;
}
}
import java.util.*;
import java.io.*;
import java.beans.*;
public class test {
public test() {}
public static void main(String args[]) {
test tes = new test();
Address array[]=tes.readObjects();
for(int i=0;i<array.length;i+=1)
{
tes.add(array[i]);
}
Address add=new Address();
add.setTest(args[0]);
tes.add(add);
}
public Address[] readObjects()
{
Vector vect=new Vector();
try {
XMLDecoder d = new XMLDecoder(
new BufferedInputStream(
new FileInputStream("addresses
while (true) {
Address add = (Address) d.readObject();
if (add == null) {
break;
}
vect.add(add);
}
d.close();
}
catch (Exception ex) {
System.err.println(ex);
}
return (Address[])vect.toArray(ne
}
public void add(Object object) {
try {
XMLEncoder e = new XMLEncoder(
new BufferedOutputStream(
new FileOutputStream("addresse
e.writeObject(new Address());
e.close();
}
catch (Exception ex) {
}
}
}
You'd be much better off serializing a List of Address
List addresses = new ArrayList();
addresses.add(new Address(name, phone, email));
ooOut.writeObject(addresse s);
........
List addresses = (List)ooIn.readObject(addr essList);
// append one
addresses.add(new Address(name2, phone2, email2));
ooOut.writeObject(addresse s);
List addresses = new ArrayList();
addresses.add(new Address(name, phone, email));
ooOut.writeObject(addresse
........
List addresses = (List)ooIn.readObject(addr
// append one
addresses.add(new Address(name2, phone2, email2));
ooOut.writeObject(addresse
> You'd be much better off serializing a List of Address
Already mentioned.
and it's not a case of being better off, thats how it needs to be done.
Already mentioned.
and it's not a case of being better off, thats how it needs to be done.
This must be your final model, if u depend on XMLEncoder and XMLDecoder
import java.util.*;
import java.io.*;
import java.beans.*;
public class test {
public test() {}
public static void main(String args[]) {
test tes = new test();
Address array[] = tes.loadObjects();
Address add = new Address();
add.setTest(args[0]);
tes.add(array,add);
tes.readObjects();
}
public Address[] loadObjects() {
Vector vect = new Vector();
try {
XMLDecoder d = new XMLDecoder(
new BufferedInputStream(
new FileInputStream("addresses .xml")));
while (true) {
Address add = (Address) d.readObject();
if (add == null) {
break;
}
vect.add(add);
System.err.println(add.get Test());
}
d.close();
}
catch (Exception ex) {
System.err.println(ex);
}
return (Address[]) vect.toArray(new Address[0]);
}
public void readObjects() {
try {
XMLDecoder d = new XMLDecoder(
new BufferedInputStream(
new FileInputStream("addresses .xml")));
while (true) {
Address add = (Address) d.readObject();
if (add == null) {
break;
}
System.err.println(add.get Test());
}
d.close();
}
catch (Exception ex) {
}
}
public void add(Address[] array, Object object) {
try {
XMLEncoder e = new XMLEncoder(
new BufferedOutputStream(
new FileOutputStream("addresse s.xml")));
for (int i = 0; i < array.length; i++) {
e.writeObject(array[i]);
}
e.writeObject(object);
e.close();
}
catch (Exception ex) {
}
}
}
__________________________ __________ __________ __________ __________ __________ __________ ___
public class Address implements Serializable
{
private String test;
public Address() {
}
public void setTest(String str)
{
test=str;
}
public String getTest()
{
return test;
}
}
import java.util.*;
import java.io.*;
import java.beans.*;
public class test {
public test() {}
public static void main(String args[]) {
test tes = new test();
Address array[] = tes.loadObjects();
Address add = new Address();
add.setTest(args[0]);
tes.add(array,add);
tes.readObjects();
}
public Address[] loadObjects() {
Vector vect = new Vector();
try {
XMLDecoder d = new XMLDecoder(
new BufferedInputStream(
new FileInputStream("addresses
while (true) {
Address add = (Address) d.readObject();
if (add == null) {
break;
}
vect.add(add);
System.err.println(add.get
}
d.close();
}
catch (Exception ex) {
System.err.println(ex);
}
return (Address[]) vect.toArray(new Address[0]);
}
public void readObjects() {
try {
XMLDecoder d = new XMLDecoder(
new BufferedInputStream(
new FileInputStream("addresses
while (true) {
Address add = (Address) d.readObject();
if (add == null) {
break;
}
System.err.println(add.get
}
d.close();
}
catch (Exception ex) {
}
}
public void add(Address[] array, Object object) {
try {
XMLEncoder e = new XMLEncoder(
new BufferedOutputStream(
new FileOutputStream("addresse
for (int i = 0; i < array.length; i++) {
e.writeObject(array[i]);
}
e.writeObject(object);
e.close();
}
catch (Exception ex) {
}
}
}
__________________________
public class Address implements Serializable
{
private String test;
public Address() {
}
public void setTest(String str)
{
test=str;
}
public String getTest()
{
return test;
}
}
ASKER
Sudhakar,
Thanks for ur lot of suggestions, but we needed simple core java program.
Thanks for ur lot of suggestions, but we needed simple core java program.
so your code would end up looking something like:
static void readAddress()throws Exception
{
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("C:/AddBo ok.txt"));
BufferedReader br= new BufferedReader(new InputStreamReader(System.i n));
AddressBook aBook = new AddressBook ();
String name,phone,email;
System.out.print("\nEnter name:");
name=br.readLine();
System.out.print("\nEnter phone:");
phone=br.readLine();
System.out.print("\nEnter email:");
email=br.readLine();
aBook.addAddress(name,phon e,email);
oos.writeObject(aBook);
oos.close();
}
...
class AddressBook extends ArrayList
{
public void addAddress(String name,String phone,String email) throws Exception
{
Address address=new Address();
address.set(name,phone,ema il);
add(address);
}
...
static void readAddress()throws Exception
{
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("C:/AddBo
BufferedReader br= new BufferedReader(new InputStreamReader(System.i
AddressBook aBook = new AddressBook ();
String name,phone,email;
System.out.print("\nEnter name:");
name=br.readLine();
System.out.print("\nEnter phone:");
phone=br.readLine();
System.out.print("\nEnter email:");
email=br.readLine();
aBook.addAddress(name,phon
oos.writeObject(aBook);
oos.close();
}
...
class AddressBook extends ArrayList
{
public void addAddress(String name,String phone,String email) throws Exception
{
Address address=new Address();
address.set(name,phone,ema
add(address);
}
...
Actually more like this:
class AddBook
{
private static AddressBook aBook;
public static void main (String [] arguments)throws Exception
{
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("C:/AddBoo k.txt"));
aBook = (AddressBook) ois.readObject();
ois.close();
int option;
boolean again=true;
String temp;
BufferedReader input= new BufferedReader(new InputStreamReader(System.i n));
while(again)
{
System.out.println("\n\n ADDRESS BOOK");//Menu items to be displayed
System.out.println(" ------------");
System.out.println("\n 1. ADD");
System.out.println(" 2. LIST");
System.out.println(" 5. EXIT");
System.out.print("\n\n Enter your option: ");
temp=input.readLine();
option=(isNumeric(temp)?In teger.pars eInt(temp) :0);
switch(option)
{
case 1: //To Add new contacts to Addres Book
readAddress();
break;
case 2: //To Display contacts in the Addres Book
displayAddress();
break;
case 5://To exit from the Addres Book
again=false;
break;
default://Other than option given
System.out.println("\n Invalid option.");
}
System.out.print("\n\n\n\n Press enter to continue...");
temp=input.readLine();
}
}
static void displayAddress()throws Exception
{
aBook.displayAddress();
}
static void readAddress()throws Exception
{
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("C:/AddBo ok.txt",tr ue));
BufferedReader br= new BufferedReader(new InputStreamReader(System.i n));
String name,phone,email;
System.out.print("\nEnter name:");
name=br.readLine();
System.out.print("\nEnter phone:");
phone=br.readLine();
System.out.print("\nEnter email:");
email=br.readLine();
aBook.addAddress(name,phon e,email);
oos.writeObject(aBook);
oos.close();
}
static boolean isNumeric(String str)throws Exception
{
try
{ int t=Integer.parseInt(str);
return true;
}
catch(NumberFormatExceptio n e) {return false;}
}
}
class AddressBook extends ArrayList
{
public void addAddress(String name,String phone,String email) throws Exception
{
Address address=new Address();
address.set(name,phone,ema il);
add(address);
}
public void displayAddress()
{
for(int i=0;i<this.size();i++)
{
Address address =(Address)this.get(i);
address.display();
}
System.out.println("No of Records:" + this.size());
}
}
class AddBook
{
private static AddressBook aBook;
public static void main (String [] arguments)throws Exception
{
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("C:/AddBoo
aBook = (AddressBook) ois.readObject();
ois.close();
int option;
boolean again=true;
String temp;
BufferedReader input= new BufferedReader(new InputStreamReader(System.i
while(again)
{
System.out.println("\n\n ADDRESS BOOK");//Menu items to be displayed
System.out.println(" ------------");
System.out.println("\n 1. ADD");
System.out.println(" 2. LIST");
System.out.println(" 5. EXIT");
System.out.print("\n\n Enter your option: ");
temp=input.readLine();
option=(isNumeric(temp)?In
switch(option)
{
case 1: //To Add new contacts to Addres Book
readAddress();
break;
case 2: //To Display contacts in the Addres Book
displayAddress();
break;
case 5://To exit from the Addres Book
again=false;
break;
default://Other than option given
System.out.println("\n Invalid option.");
}
System.out.print("\n\n\n\n
temp=input.readLine();
}
}
static void displayAddress()throws Exception
{
aBook.displayAddress();
}
static void readAddress()throws Exception
{
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("C:/AddBo
BufferedReader br= new BufferedReader(new InputStreamReader(System.i
String name,phone,email;
System.out.print("\nEnter name:");
name=br.readLine();
System.out.print("\nEnter phone:");
phone=br.readLine();
System.out.print("\nEnter email:");
email=br.readLine();
aBook.addAddress(name,phon
oos.writeObject(aBook);
oos.close();
}
static boolean isNumeric(String str)throws Exception
{
try
{ int t=Integer.parseInt(str);
return true;
}
catch(NumberFormatExceptio
}
}
class AddressBook extends ArrayList
{
public void addAddress(String name,String phone,String email) throws Exception
{
Address address=new Address();
address.set(name,phone,ema
add(address);
}
public void displayAddress()
{
for(int i=0;i<this.size();i++)
{
Address address =(Address)this.get(i);
address.display();
}
System.out.println("No of Records:" + this.size());
}
}
>>Thanks for ur lot of suggestions, but we needed simple core java program.
Serialization using XMLEncoder and XMLDecoder model is very easy and simple to understand
Serialization using XMLEncoder and XMLDecoder model is very easy and simple to understand
try this one, in option 2, i can list down all records.
Please note to delete the address.txt before you run the application.
package ee;
import java.io.*;
import java.util.*;
class AddressBook extends ArrayList
{
public void addAddress(ObjectOutputStr eam oos,String name,String phone,String email) throws Exception
{
Address address=new Address();
address.set(name,phone,ema il);
oos.writeObject(address);
}
public void loadAddress(ObjectInputStr eam ois) throws Exception
{
Address address;
boolean again=true;
while(again)
{
try
{
address=(Address)ois.readO bject();
this.add(address);
}
catch(java.io.EOFException e){
again=false;
}
//again=false;}
}
ois.close();
}
public void displayAddress()
{
for(int i=0;i<this.size();i++)
{
Address address =(Address)this.get(i);
address.display();
}
System.out.println("No of Records:" + this.size());
}
}
package ee;
import java.io.*;
public class Address implements Serializable
{
String name;
String phone;
String email;
public void set(String nAme,String Phone,String Email)
{
name=nAme;
phone=Phone;
email=Email;
}
public void display()
{
System.out.println("\n" + name +putChar(" ",25-name.length())+ phone + putChar(" ",15-phone.length())+ email +putChar(" ",15-email.length()));
}
private static String putChar(String chr,int no)//It returns a string of given char no of times
{
String s="";
for (int i=0;i<no ;i++ ){s=s+ chr;}
return s;
}
}
package ee;
import java.io.*;
class AddBook
{
public static void main (String [] arguments)throws Exception
{
ObjectOutputStream oos=null;
try{oos = new ObjectOutputStream(new FileOutputStream("C:/AddBo ok.txt",tr ue));}
catch (Exception e){System.out.println(e);}
int option;
boolean again=true;
String temp;
BufferedReader input= new BufferedReader(new InputStreamReader(System.i n));
while(again)
{
System.out.println("\n\n ADDRESS BOOK");//Menu items to be displayed
System.out.println(" ------------");
System.out.println("\n 1. ADD");
System.out.println(" 2. LIST");
System.out.println(" 5. EXIT");
System.out.print("\n\n Enter your option: ");
temp=input.readLine();
option=(isNumeric(temp)?In teger.pars eInt(temp) :0);
switch(option)
{
case 1: //To Add new contacts to Addres Book
readAddress(oos);
break;
case 2: //To Display contacts in the Addres Book
displayAddress();
break;
case 5://To exit from the Addres Book
again=false;
break;
default://Other than option given
System.out.println("\n Invalid option.");
}
System.out.print("\n\n\n\n Press enter to continue...");
temp=input.readLine();
}
}
static void displayAddress()throws Exception
{
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("C:/AddBoo k.txt"));
AddressBook aBook = new AddressBook ();
aBook.loadAddress(ois);
aBook.displayAddress();
ois.close();
}
static void readAddress(ObjectOutputSt ream oos)throws Exception
{
BufferedReader br= new BufferedReader(new InputStreamReader(System.i n));
AddressBook aBook = new AddressBook ();
String name,phone,email;
System.out.print("\nEnter name:");
name=br.readLine();
System.out.print("\nEnter phone:");
phone=br.readLine();
System.out.print("\nEnter email:");
email=br.readLine();
aBook.addAddress(oos,name, phone,emai l);
}
static boolean isNumeric(String str)throws Exception
{
try
{ int t=Integer.parseInt(str);
return true;
}
catch(NumberFormatExceptio n e) {return false;}
}
}
Please note to delete the address.txt before you run the application.
package ee;
import java.io.*;
import java.util.*;
class AddressBook extends ArrayList
{
public void addAddress(ObjectOutputStr
{
Address address=new Address();
address.set(name,phone,ema
oos.writeObject(address);
}
public void loadAddress(ObjectInputStr
{
Address address;
boolean again=true;
while(again)
{
try
{
address=(Address)ois.readO
this.add(address);
}
catch(java.io.EOFException
again=false;
}
//again=false;}
}
ois.close();
}
public void displayAddress()
{
for(int i=0;i<this.size();i++)
{
Address address =(Address)this.get(i);
address.display();
}
System.out.println("No of Records:" + this.size());
}
}
package ee;
import java.io.*;
public class Address implements Serializable
{
String name;
String phone;
String email;
public void set(String nAme,String Phone,String Email)
{
name=nAme;
phone=Phone;
email=Email;
}
public void display()
{
System.out.println("\n" + name +putChar(" ",25-name.length())+ phone + putChar(" ",15-phone.length())+ email +putChar(" ",15-email.length()));
}
private static String putChar(String chr,int no)//It returns a string of given char no of times
{
String s="";
for (int i=0;i<no ;i++ ){s=s+ chr;}
return s;
}
}
package ee;
import java.io.*;
class AddBook
{
public static void main (String [] arguments)throws Exception
{
ObjectOutputStream oos=null;
try{oos = new ObjectOutputStream(new FileOutputStream("C:/AddBo
catch (Exception e){System.out.println(e);}
int option;
boolean again=true;
String temp;
BufferedReader input= new BufferedReader(new InputStreamReader(System.i
while(again)
{
System.out.println("\n\n ADDRESS BOOK");//Menu items to be displayed
System.out.println(" ------------");
System.out.println("\n 1. ADD");
System.out.println(" 2. LIST");
System.out.println(" 5. EXIT");
System.out.print("\n\n Enter your option: ");
temp=input.readLine();
option=(isNumeric(temp)?In
switch(option)
{
case 1: //To Add new contacts to Addres Book
readAddress(oos);
break;
case 2: //To Display contacts in the Addres Book
displayAddress();
break;
case 5://To exit from the Addres Book
again=false;
break;
default://Other than option given
System.out.println("\n Invalid option.");
}
System.out.print("\n\n\n\n
temp=input.readLine();
}
}
static void displayAddress()throws Exception
{
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("C:/AddBoo
AddressBook aBook = new AddressBook ();
aBook.loadAddress(ois);
aBook.displayAddress();
ois.close();
}
static void readAddress(ObjectOutputSt
{
BufferedReader br= new BufferedReader(new InputStreamReader(System.i
AddressBook aBook = new AddressBook ();
String name,phone,email;
System.out.print("\nEnter name:");
name=br.readLine();
System.out.print("\nEnter phone:");
phone=br.readLine();
System.out.print("\nEnter email:");
email=br.readLine();
aBook.addAddress(oos,name,
}
static boolean isNumeric(String str)throws Exception
{
try
{ int t=Integer.parseInt(str);
return true;
}
catch(NumberFormatExceptio
}
}
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
fredwangus,
But, I wanted records to be permenant in the file.
But, I wanted records to be permenant in the file.
did u try the changes I posted, they should meet your needs.
try my code.
Copy and paste.
Bye, Giant.
Copy and paste.
Bye, Giant.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ramnram,
copy, paste, compile, execute the code I post.
It goes good and solve your problem.
Bye, Giant.
copy, paste, compile, execute the code I post.
It goes good and solve your problem.
Bye, Giant.
ASKER
let me analyze all ur codes.
just giv me some time.
just giv me some time.
:)
thanks :)
ASKER
U guys deserved it.
:)
Object object = new javax.swing.JButton("push me");
try {
// Serialize to a file
ObjectOutput out = new ObjectOutputStream(new FileOutputStream("filename
out.writeObject(object);
out.close();
// Serialize to a byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream() ;
out = new ObjectOutputStream(bos) ;
out.writeObject(object);
out.close();
// Get the bytes of the serialized object
byte[] buf = bos.toByteArray();
} catch (IOException e) {
}