Created
June 5, 2015 03:35
-
-
Save ron623/1aa5a9dff07aee6269ac to your computer and use it in GitHub Desktop.
Serializable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package transient_test; | |
import java.io.File; | |
import java.io.FileInputStream; | |
import java.io.FileOutputStream; | |
import java.io.ObjectInputStream; | |
import java.io.ObjectOutputStream; | |
import java.io.Serializable; | |
// transient修飾子を指定したフィールドが直列化されないことを証明するためのクラス | |
public class Tra implements Serializable { | |
// serialVersionUID:どのクラスを元に作成されたのかを検証するための番号 | |
// これかかないとInvalidClassExceptionになる | |
private static final long serialVersionUID = -5029544331453326074L; | |
public final int num; | |
public transient final int tmp; | |
// イニシャライザ | |
public Tra(int num, int tmp) { | |
// インスタンス化するときにnum,tmpにそれぞれ引数を代入 | |
this.num = num; | |
this.tmp = tmp; | |
} | |
// toString()メソッドのオーバーライド | |
public String toString() { | |
// 出力用にnumとtmpを連結してString型に | |
return "num=" + num + ",tmp=" + tmp; | |
} | |
} | |
class Test { | |
// オブジェクトの読み書きメソッド | |
public static void main(String[] args) throws Exception { | |
// ファイル名 | |
String fileName = "test.txt"; | |
File file = new File(fileName); | |
// 既にファイルが存在するときはそれを表示 | |
if (file.exists()) { | |
FileInputStream fin = new FileInputStream(file); | |
ObjectInputStream oin = new ObjectInputStream(fin); | |
// オブジェクトよみこみ | |
System.out.println(oin.readObject()); | |
System.out.println("よみこみ完了"); | |
oin.close(); | |
fin.close(); | |
// ファイルが存在しないときは新規作成 | |
} else { | |
FileOutputStream fout = new FileOutputStream(file); | |
ObjectOutputStream oout = new ObjectOutputStream(fout); | |
// Traオブジェクトのインスタンス化 | |
Tra tra = new Tra(100, 500); | |
// オブジェクト書き込み | |
oout.writeObject(tra); | |
oout.close(); | |
fout.close(); | |
System.out.println(tra + "かきこみ完了"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment