ハードディスク(HDD)にオブジェクトを格納します.Externalizable

2704 ワード

Javaのオブジェクトはメモリだけでなく、ハードディスク(HDD)にもアクセスできます.Externalizableインタフェースを実装する必要があります.簡単な使い方を説明します.
まず、クラス実装Externalizableインタフェースを書く
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;

public class Car implements Externalizable{
	public Car(){}
	public Car(int id,int price){
		this.id = id;
		this.price = price;
	}
 private int id;
 public int getId() {
	return id;
}
public void setId(int id) {
	this.id = id;
}
public int getPrice() {
	return price;
}
public void setPrice(int price) {
	this.price = price;
}
private int price;

//       
@Override
public void writeExternal(out) throws IOException {
	// TODO Auto-generated method stub
	System.out.println("    ");
	out.writeObject(id);//ObjectOutput                
	out.writeObject(price);
        out.flush();
        out.close();

 }
//        
 @Override
public void readExternal(ObjectInput in) throws IOException,
		ClassNotFoundException {
	// TODO Auto-generated method stub
	System.out.println("    ");
	this.id = (int)in.readObject();
	this.price = (int)in.readObject();
	return;
}
}

呼び出し方法
		Externalizable car1 = new Car(8,2);
		car1.writeExternal(new ObjectOutputStream(new FileOutputStream(new File("d:/exteral.txt"))));
		Car car2 = new Car();
		car2.readExternal(new ObjectInputStream(new FileInputStream(new File("d:/exteral.txt"))));
		System.out.println(car2.getId()+" "+car2.getPrice());

しかし、目測Serializableも同様の機能を実現することができ、コードは以下の通りである.
import java.io.Serializable;

public class Person implements Serializable {
	private String name;
	private int age;
	private int id;
	
	public Person(){}
	public Person(String name,int age,int id){
		this.name = name;
		this.age=age;
		this.id=id;
	}
	
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	
	
	
}

よびだし
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File("d:/person1.txt")));
		objectOutputStream.writeObject(new Person("haha",25,1));
		objectOutputStream.close();
		
		ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(new File("d:/person1.txt")));
		Person p1 = (Person) objectInputStream.readObject();
		objectInputStream.close();
		System.out.println(p1.getName()+p1.getAge()+p1.getId());