关于android 将对象写入文件以及从文件读取对象

时间:2021-12-16 05:32:12

由于项目需求,需要保存用户登录过的一些配置,当下次登录的时候读取登录过的配置,所以简单的SharePreferences没有办法满足,于是找到了Java中ObjectInputStream 与 ObjectOutputStream这两个包装类可用于输入流中读取对象类数据和将对象类型的数据写入到底层输入流 。ObjectInputStream 与 ObjectOutputStream 类所读写的对象必须实现了 Serializable 接口。

 /**
* 文件转化为Object
* @param fis
* @return byte[]
*/
public static Object file2Object(FileInputStream fis/*String fileName*/) { //FileInputStream fis = null;
ObjectInputStream ois = null;
try {
//fis = new FileInputStream(fileName);
ois = new ObjectInputStream(fis);
Object object = ois.readObject();
return object;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (ois != null) {
try {
ois.close();
} catch (IOException e2) {
e2.printStackTrace();
}
}
}
return null;
} /**
*object转化为文件
* @param obj
* @param fos
*/
public static void object2File(Object obj, FileOutputStream fos/*String outputFile*/) {
ObjectOutputStream oos = null;
//FileOutputStream fos = null;
try {
//fos = new FileOutputStream(new File(outputFile));
oos = new ObjectOutputStream(fos);
oos.writeObject(obj);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (oos != null) {
try {
oos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e2) {
e2.printStackTrace();
}
}
}
}
/**
* Created by james.li on 13-9-25.
*/
public class LoginUserInfo implements Serializable{
/**
* serialVersionUID
*/
private static final long serialVersionUID = -6846034858002233878L; private String userCC; private String userSN; private String productKind; public LoginUserInfo() {
} public LoginUserInfo(String userCC, String userSN,String productKind) {
this.userCC = userCC;
this.userSN = userSN;
this.productKind = productKind;
} public String getUserCC() {
return this.userCC;
}
public String getUserSN() {
return this.userSN;
}
public String getProductKind() {
return this.productKind;
} public void setUserCC(String userCC) {
this.userCC = userCC;
} public void setUserSN(String userSN) {
this.userSN = userSN;
} public void setProductKind(String productKind) {
this.productKind = productKind;
} @Override
public String toString() {
return "userCC=[ " + userCC + " ] userSN=[ " + userSN + " ] productKind=[ "
+ productKind + "] .";
}
}

使用

    public static final String USER_LOGIN_INFO = "loginUserInfo.obj";
try {
//先读出来
FileInputStream is = openFileInput(com.launch.rcu.util.CommonUtil.USER_LOGIN_INFO);
userLoginList = (List<LoginUserInfo>) com.launch.rcu.util.CommonUtil.file2Object(is);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//写
FileOutputStream os = null;
try {
os = openFileOutput(CommonUtil.USER_LOGIN_INFO,MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
CommonUtil.object2File(userLoginList, os);

ok,就这样可以了