その後、同じ型のインスタンスを再作成するために、このファイルを使用してファイルにオブジェクトの状態を保存することを意味する、シリアライズを使用することができます。
public class Employee implements java.io.Serializable
{
public String name;
public String address;
public transient int SSN;
public int number;
public void mailCheck()
{
System.out.println("Mailing a check to " + name + " " + address);
}
}
従業員クラスを例にとると、通常はnew演算子で1つの従業員インスタンスを作成し、いくつかのプロパティを設定する必要があります。
public class JavaApplication40 {
static Employee master;
static Employee copy;
public static void main(String[] args) {
master = new Employee();
master.name = "Reyan Ali";
master.address = "Phokka Kuan, Ambehta Peer";
master.SSN = 11122333;
master.number = 101;
serialize();
deserializing();
}
最後の2つの方法があなたに代わって行います。
public static void serialize()
{
try{
FileOutputStream fileOut = new FileOutputStream("c:\\master.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(master);
out.close();
fileOut.close();
System.out.printf("Serialized data is saved in /tmp/master.ser");
}catch(IOException i){
i.printStackTrace();
}
}
public static void deserializing()
{
try{
FileInputStream fileIn = new FileInputStream("c:\\master.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
copy = (Employee) in.readObject();
in.close();
fileIn.close();
}catch(IOException i){
i.printStackTrace();
return;
}catch(ClassNotFoundException c){
System.out.println("Employee class not found");
c.printStackTrace();
return;
}
System.out.println("Deserialized Employee...");
System.out.println("Name: " + copy.name);
System.out.println("Address: " + copy.address);
System.out.println("SSN: " + copy.SSN);
System.out.println("Number: " + copy.number);
}
これは、ファイルシステム にマスターオブジェクトの状態を保存して、ファイルに保存されているのと同じデータを使用したコピー・オブジェクトを作成するになります。
願っています。
Employeeクラスはjava.io.Serializableを実装する必要があります。 –
このクラスの変数もファイルに書き込まれます。トランジェントとして宣言しない限り。 –
一時的な文字列userPassword; –