Skip to content

Instantly share code, notes, and snippets.

@seriwb
Created March 21, 2014 18:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seriwb/9692316 to your computer and use it in GitHub Desktop.
Save seriwb/9692316 to your computer and use it in GitHub Desktop.
Mapオブジェクトをファイルにバイトで書き込んだものをファイル読み込みして再度使えるかをテストしたプログラム
package groovytest
/**
* Mapオブジェクトをファイルにバイトで書き込んだものを
* ファイル読み込みして再度使えるかをテストしたプログラム
*
* 結論:できる
*/
// データ格納用
HashMap dataMap = [:]
dataMap.put("hoge1", "foooooooooo")
println "Mapの初期状態:" + dataMap
// ファイルがあればそれを読み込み、初期化をスキップ
def filebytedata = new File("src/groovytest/dataMap.dat")
if (filebytedata.exists()) {
println "ファイルがある!"
// バイトデータを読み取り、dataMapに設定
byte[] tempbytes = filebytedata.readBytes()
// ファイルの中身が空だとbyte[0]が返っているため、サイズが1になる
if (tempbytes.size() == 1) {
println "ファイルの中身が空っぽだよ"
} else {
ByteArrayInputStream bais = new ByteArrayInputStream(tempbytes)
ObjectInputStream ois = new ObjectInputStream(bais)
dataMap = (HashMap) ois.readObject()
// 新しい要素を追加
dataMap.put("hoge${dataMap.size()+1}", "追加")
// 中身をすべて表示
println "Mapにデータ追加後:" + dataMap
ois.close()
bais.close()
}
}
// ファイルがない場合はデータをファイルに格納
else {
println "ファイルがない!!"
dataMap.put("hoge2", "bazzzzzzzzzz")
// 中身をすべて表示
println "初期化処理で要素を追加:" + dataMap
// 書き込み用のbyte配列を作成
ByteArrayOutputStream baos = new ByteArrayOutputStream()
ObjectOutputStream oos = new ObjectOutputStream(baos)
oos.writeObject(dataMap)
byte[] bytes= baos.toByteArray()
// ファイルを作成してデータを書き込み
filebytedata.createNewFile()
FileOutputStream fos = new FileOutputStream(filebytedata)
fos.write(bytes)
fos.close()
oos.close()
baos.close()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment