Archive for October, 2012

Writing Objects to an Input or Output Stream with Java

Serialization in Java is the process by which an application can transmit an entire object (including state) over a communications channel. Prior to being transmitted all data, including primitive types must be marshaled. Marshaling (serializing) is simply the process of breaking data into bytes so that they can be transmitted over a channel. Once the data is transmitted, the receiving end unmarshals (deserializes) the data into its original form.

Object deserialization is more complex than primitive unmarshaling because objects often have references to other objects, and thus it becomes necessary to keep track of referenced objects in order to fully reconstruct the object after serialization. Fortunately there are classes that manage the serialization for us. These are the ObjectInputStream and ObjectOutputStream classes. All you will need to do is ensure that the class you wish to write to a file implements the Serializable interface. Below is an example program that uses the ObjectOutputStream to write an object to a file. It then uses the ObjectInputStream to read the object from a file into a different instance variable.

 import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 * A simple object serialization example
 */
public class ObjectToFile {
	private File file = null;
	private FileOutputStream fos = null;
	private FileInputStream fis = null;
	private ObjectOutputStream oos = null;
	private ObjectInputStream iis = null;
	private TwoPoint tp;
	private TwoPoint tp2;

	public ObjectToFile() {
		tp = new TwoPoint(Math.random(), Math.random());
	}

	public static void main(String[] args) throws IOException,
			ClassNotFoundException {
		ObjectToFile otf = new ObjectToFile();
		if (args.length <= 0) {
			otf.openOutputFile(null); // using default file
		} else {
			otf.openOutputFile(args[0]); // providing filename
		}
		otf.writeInnerClassState();
		otf.openInputFile(null);
		otf.closeFile();

	}

	// open file
	private void openInputFile(String filename) throws IOException,
			ClassNotFoundException {
		if ((filename == null) || filename.trim().equals("")) {
			file = new File("output.txt");
			System.out.println("Reading from:" + file.getAbsolutePath());
		} else {
			file = new File(filename);
			System.out.println("Reading from: " + file.getAbsolutePath());
		}
		fis = new FileInputStream(file);
		iis = new ObjectInputStream(fis);
		tp2 = (TwoPoint) iis.readObject();
		System.out.println("tp2: " + tp2.toString());
	}

	public void openOutputFile(String filename) throws IOException {
		if ((filename == null) || filename.trim().equals("")) {
			file = new File("output.txt");
			System.out.println("Writing to default file:"
					+ file.getAbsolutePath());
		} else {
			file = new File(filename);
			System.out.println("Writing to file: " + file.getAbsolutePath());
		}
		fos = new FileOutputStream(file, false);
		oos = new ObjectOutputStream(fos);
	}

	public void writeInnerClassState() throws IOException {
		oos.writeObject(tp);
		System.out.println("tp: " + tp.toString());
	}

	private void closeFile() {
		if (fos != null) {
			try {
				fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		if (fis != null) {
			try {
				fis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public TwoPoint getTp() {
		return tp;
	}
}

class TwoPoint implements Serializable {
	private static final long serialVersionUID = -4233775519934013146L;
	private double x;
	private double y;

	public TwoPoint(double x, double y) {
		this.x = x;
		this.y = y;
	}

	public double getX() {
		return x;
	}

	public double getY() {
		return y;
	}

	public void setX(double x) {
		this.x = x;
	}

	public void setY(double y) {
		this.y = y;
	}

	public String toString() {

		return "[TwoPoint:x=" + this.x + ", y=" + y + "]";
	}
}
 

Comments Trackbacks / Pingbacks (14)