您的位置:首页 > 其它

Serializable 对象文件存储读取

2013-06-27 16:04 393 查看
网上很多资料,自己写了一份,备份留档用
/*
* Copyright (c) 2013 NeuLion, Inc. All Rights Reserved.
*/
package com.neulion.android.nfl.library.util;

import java.io.File;
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 android.content.Context;
import android.os.Environment;

import com.neulion.android.common.connection.exception.ConnectionException;
import com.neulion.android.common.connection.exception.NotFoundException;
import com.neulion.android.common.parser.CommonParser;
import com.neulion.android.common.parser.exception.ParserException;
import com.neulion.android.framework.application.config.ConfigManager;
import com.neulion.android.nfl.library.bean.messaging.AppMessages;

public class NFLMessageHelper
{

// private static final String KEY = "NFLMessageUtil";
private static final long ONE_DAY = 24 * 60 * 60 * 1000;

public static AppMessages getNFLMessage(Context context)
{
final String filePath = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/" + "app_message.dat";

final File file = new File(filePath);

AppMessages appMsg = null;

if (!file.exists())
{
try
{
file.createNewFile();

appMsg = getRemoteAppMessages(context);

saveAppMessage(file, appMsg);
}
catch (Exception e)
{
e.printStackTrace();
}

return appMsg;
}

ObjectInputStream in = null;

try
{
in = new ObjectInputStream(new FileInputStream(file));

appMsg = (AppMessages) in.readObject();

in.close();
}
catch (Exception e)
{
e.printStackTrace();
}

final long currentStamp = System.currentTimeMillis();

if (appMsg == null || (currentStamp - appMsg.getStamp()) >= ONE_DAY)
{
try
{
appMsg = getRemoteAppMessages(context);

saveAppMessage(file, appMsg);
}
catch (Exception e)
{
e.printStackTrace();
}
}

return appMsg;
}

private static AppMessages getRemoteAppMessages(Context context)
throws ConnectionException, NotFoundException, ParserException
{
final String deviceType = DeviceTypeHelper.isPhone(context) ? "triggerRules_phone"
: "triggerRules_tablet";

final String url = ConfigManager.getValue(deviceType);

return CommonParser.parse(url, new AppMessages());
}

private static void saveAppMessage(File file, AppMessages appMsg)
throws FileNotFoundException, IOException
{
final ObjectOutputStream out = new ObjectOutputStream(
new FileOutputStream(file));

appMsg.setStamp(System.currentTimeMillis());

out.writeObject(appMsg);

out.close();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: