Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

simple read/write

Status
Not open for further replies.

edifreak

IS-IT--Management
Apr 7, 2003
74
AU
Greetings,

I'd like to know if someone here can help me with using the ObjectInputStream and ObjectOutputStream classes for reading from or writing to the file.

My data file has the following format
Pyrmont:2009:2000
Mortdale:2223:2000
Kogarah:2217:2000

Three fields, each separated by a character :

i've used BufferedReader and readLine to do the job fine... but i would like to covert them to seiralizable objects.

Can anyone provide me with an example of how to do this pls?

Thanks in advance.
 
extend serializable, and Objects (not primative) that are a part of your class should also extend serializable. Then implement:
Code:
 private void writeObject(java.io.ObjectOutputStream out)
     throws IOException
 private void readObject(java.io.ObjectInputStream in)
     throws IOException, ClassNotFoundException;
As per:

[plug=shameless]
[/plug]
 
Hiya!

I tired to implement the write and read function... when i try to read the file, it is not showing the entire content of the file. Only the last entered record is shown.
it should add each record not replace existing records?

Sorry newbie here with coding...

Below is my code..

Code:
	public void tryInsert(String xp1, String xp2, String xp3)
	{


			Vector newData2 = new Vector();
			try {
				String[] parts = {xp1, xp2, xp3};
				AddressRecord arec2 = new AddressRecord(parts[0], parts[1], parts[2]);
				newData2.add(arec2);
				tp.updateDataSet(newData2);
				tabbedPane.setEnabledAt(2, true); // can now tab to pane
				switchToTable();

				FileOutputStream fos = new FileOutputStream("serial");
				ObjectOutputStream oos = new ObjectOutputStream(fos);

				oos.writeObject(arec2);
				oos.flush();
				oos.close();
			}

		catch(Exception ioe) {

		}



	}

	public void tryRead()
	{
		Vector newData = new Vector();

		try {
			FileInputStream fis = new FileInputStream("serial");
			ObjectInputStream ois = new ObjectInputStream(fis);

			for(;;) {
			AddressRecord arec;
			arec = (AddressRecord) ois.readObject();

			System.out.println(arec);
			ois.close();
			}

		}

		catch(Exception ioe) {

		}



	}


This is the address record class

Code:
import java.io.*;

public class AddressRecord implements Serializable {

	String suburb;
	String postcode;
	String newdata;

	public AddressRecord(String sub, String pc, String nd){
		this.suburb = sub;
		this.postcode = pc;
		this.newdata = nd;
	}

	public String toString() {
		return suburb + postcode + newdata;

	}
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top