Assume we have one value object which named "User".
It has two attributes, including userName and password.
public class User implements java.io.Serializable{
private String userName;
private String password;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
And we have one requirement to transfr this object to the specific receiver. Here has one picture to describe.
picture source: http://www.churchillobjects.com/c/11009.html
Then here has one sample to demo how to do this.
import java.io.ObjectOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class ObjectTransferExample {
//sender's method
public void send() throws SecurityException, IOException {
//declare one User object, and set data to userName and password attribute
User user = new User();
user.setUserName("Albert");
user.setPassword("123456789");
FileOutputStream out = new FileOutputStream("User");
ObjectOutputStream s = new ObjectOutputStream(out);
//write object name ans user object to ObjectOutputStream
s.writeObject("User");
s.writeObject(user);
s.flush();
}
//receiever's method
public void receieve() throws FileNotFoundException, IOException,
ClassNotFoundException, IOException {
FileInputStream in = new FileInputStream("User");
ObjectInputStream s = new ObjectInputStream(in);
//read the object name
String objectName = (String) s.readObject();
//retrieve the User object
User user = (User) s.readObject();
//print the object name and the User object's content
System.out.println("---------------------------------");
System.out.println("objectName="+objectName);
System.out.println("user name=" + user.getUserName());
System.out.println("password=" + user.getPassword());
System.out.println("---------------------------------");
}
public static void main(String[] args) throws IOException, SecurityException,
ClassNotFoundException, FileNotFoundException, IOException {
ObjectTransferExample example = new ObjectTransferExample();
example.send();
example.receieve();
}
}
No comments:
Post a Comment