FileMng.java
例としてList<String>型オブジェクトを、Save()メソッドでシリアライズ(ファイル保存)、
Load()メソッドでデシリアライズ(ファイル読み込み)するクラスFileMngは以下のように実装できた。
(LogMng.PrintException(e, “hogehoge”);は例外ログを残す自作クラスの処理)
package com.test;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
public class FileMng {
static final String FILE_NAME = "object.file";
/**
* シリアライズ
* オブジェクト(文字列リスト)をファイルに保存
*/
static int Save(Context context, List<String> list){
//保存
try {
//FileOutputStream outFile = new FileOutputStream(FILE_NAME);
FileOutputStream outFile = context.openFileOutput(FILE_NAME, 0);
ObjectOutputStream outObject = new ObjectOutputStream(outFile);
outObject.writeObject(list);
outObject.close();
outFile.close();
} catch (FileNotFoundException e) {
LogMng.PrintException(e, "");
} catch (IOException e) {
LogMng.PrintException(e, "");
}
return 0;
}
/**
* デシリアライズ
* ファイルからオブジェクト(文字列リスト)に読み込み
*/
static List<String> Load(Context context){
List<String> list = new ArrayList<String>();
//読み込み
try {
//FileInputStream inFile = new FileInputStream(FILE_NAME);
FileInputStream inFile = context.openFileInput(FILE_NAME);
ObjectInputStream inObject = new ObjectInputStream(inFile);
list = (ArrayList<String>)inObject.readObject();
inObject.close();
inFile.close();
} catch (FileNotFoundException e) {
LogMng.PrintException(e, "");
} catch (StreamCorruptedException e) {
LogMng.PrintException(e, "");
} catch (IOException e) {
LogMng.PrintException(e, "");
} catch (ClassNotFoundException e) {
LogMng.PrintException(e, "");
}
return list;
}
}
利用方法
なにかしらのアクティビティから呼び出すコードはこんな感じ。
Save()メソッド、Load()メソッド内でFileOutput/InputStreamの生成にContextが必要なのでthisで渡している。
package com.test;
import java.util.List;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class ListActivity extends android.app.ListActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
:
(略)
:
//読み込み
List<String> list = FileMng.Load(this);
//保存
FileMng.Save(this, list);
:
(略)
:
}
