您的位置:首页 > 其它

序列化对象输入输出操作实例

2010-10-28 15:56 519 查看
/**
* 将序列化对象写入文件
* @param obj 对象
* @param path 路径
* @return 是否写入成功
*/
public static boolean writeObject2File(Object obj,String path) {
FileOutputStream ostream = null;
ObjectOutputStream p  = null;
try {
ostream = new  FileOutputStream(path);
p = new  ObjectOutputStream(ostream);
p.writeObject(obj);
p.flush();
} catch (IOException e) {
PubUtil.logDebug("序列化对象写入文件错误"+e);
return false;
}
finally{
try {
if(ostream!=null)
ostream.close();
} catch (IOException e) {
PubUtil.logDebug("关闭ostream流错误"+e);
e.printStackTrace();
}
}
return true;
}
/**
* 读取序列化对象文件
* @param path 路径及名称
* @return  对象
*/
public static Object readObjectFromFile(String path){
FileInputStream fis = null;
ObjectInputStream ois = null;
Object obj = null;
//	PubUtil.logDebug("开始读取序列化文件"+path);
try {
fis = new  FileInputStream(path);
ois = new  ObjectInputStream(fis);
obj = ois.readObject();
} catch (ClassNotFoundException e) {
PubUtil.logDebug("读取序列化对象,发生转换错误"+e);
} catch (FileNotFoundException e) {
PubUtil.logDebug("读取序列化对象错误,无该对象"+e);
} catch (IOException e) {
PubUtil.logDebug("读取序列化对象错误"+e);
}
finally{
try {
if(ois!=null){
ois.close();
}
} catch (IOException e) {
PubUtil.logDebug("关闭ois流错误"+e);
}
}
//	PubUtil.logDebug("读取结束");
return obj;
}
/**
* 将序列化对象输出为XML文件
* @param obj  序列化对象
* @param fileName  路径及文件名
*/
public static boolean objectXmlEncoder(Object obj,String fileName){
File fo = null;
FileOutputStream fos = null;
XMLEncoder encoder = null;
try {
fo = new File(fileName);
if(!fo.exists()){
String path = fileName.substring(0,fileName.lastIndexOf('.'));
File pFile = new File(path);
pFile.mkdirs();
}
fos = new FileOutputStream(fo);
encoder = new XMLEncoder(fos);
encoder.writeObject(obj);
encoder.flush();
}  catch (FileNotFoundException e) {
PubUtil.logDebug("输出序列化对象XML,发生错误"+e);
}
finally{
try {
if(encoder!=null){
encoder.close();
}
if(fos!=null){
fos.close();
}
} catch (IOException e) {
PubUtil.logDebug("关闭流错误"+e);
}
}
return true;
}
/**
* 读取序列化对象XML文件
* @param objSource
* @return
*/
public static Object objectXmlDecoder(String objSource){
//  List objList =  null;
File fin = null;
FileInputStream fis = null;
XMLDecoder decoder = null;
Object obj = null;
try {
//  objList = new ArrayList();
fin = new File(objSource);
fis = new FileInputStream(fin);
decoder = new XMLDecoder(fis);
obj = decoder.readObject();
} catch (IOException e) {
PubUtil.logDebug("读取序列化对象XML,发生错误"+e);
}
finally{
try{
if(decoder!=null){
decoder.close();
}
if(fis!=null){
fis.close();
}
}catch(IOException e){
PubUtil.logDebug("关闭流错误"+e);
}

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