java可序列化Object到XML文件中
package com.ftpgw;
import java.beans.XMLDecoder; import java.beans.XMLEncoder; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.HashMap; import java.util.Map;
public class SerializeXMLFile { public static void serializeToFile(Object obj,String filePath) { try { File file=new File(filePath); if(!(file.isFile()&&file.exists())){ file.createNewFile(); }
FileOutputStream fos = new FileOutputStream(filePath);
XMLEncoder encoder = new XMLEncoder(fos);
encoder.writeObject(obj);
encoder.close();
fos.close();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static Object deSerializeFromFile(String filePath) {
Object obj = null;
try {
File file=new File(filePath);
if(!(file.isFile()&&file.exists())){
return null;
}
FileInputStream fis = new FileInputStream(filePath);
XMLDecoder decoder = new XMLDecoder(fis);
obj= decoder.readObject();
decoder.close();
fis.close();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return obj;
}
@SuppressWarnings("unchecked")
public static void main(String args) {
Map map1 = new HashMap();
map1.put("fileName1", 20001);
map1.put("fileName2", 20002);
SerializeXMLFile.serializeToFile(map1,"H:\\map.xml");
Map map2=(Map)SerializeXMLFile.deSerializeFromFile("H:\\map.xml");
for(Object a:map2.keySet()){
Integer values=(Integer)map2.get(a.toString());
System.out.println(values.intValue());
}
}
}