ObjectOutputStream的简单用法
/**
* 写入Object数据
*
* @param fileName
* 需要写入的文件
* @param obj
* 需要写入的Object型的数据
*
*/
public static void ObjectOutputStreamMethod(String fileName, Object obj) {
ObjectOutputStream output = null;
try {
output = new ObjectOutputStream(new FileOutputStream(new File(fileName)));
output.writeObject(obj);
output.flush();
output.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
利用ObjectInputStream来读取Map形式的Object数据
<pre name="code" class="java">/**
* 读取Map形式的Object数据
*
* @param fileName
* 需要读取的文件
*/
public static void ObjectInputStreamMethod(String fileName) {
ObjectInputStream input = null;
Object obj = null;
try {
input = new ObjectInputStream(new FileInputStream(new File(fileName)));
obj = input.readObject();
if (obj == null) {
System.err.println("Object can't been reload by ObjectInputStreamMethod");
input.close();
return;
}
if (obj != null && obj instanceof Map) {
Map<?, ?> readMap = (Map<?, ?>) obj;
System.out.println("Object Description:");
for (Map.Entry<?, ?> one : readMap.entrySet()) {
System.out.printf("%s \t %s %n", one.getKey(), one.getValue());
}
input.close();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}