生成.sdua文件的时候可能会用到读写对象,贴两个方法……
/**写对象方法,参数是路径和对象*/
public static void writeObject(String outFile, Object object) {
try {
ObjectOutputStream out = new ObjectOutputStream(
new BufferedOutputStream(new FileOutputStream(outFile)));
out.writeObject(object);
out.close();
} catch (Exception e) {
System.err.println(e);
}
}
/**写对象方法,参数是对象路径,返回Object对象*/
public static Object readObject(String filePath) {
File inFile = new File(filePath);
if(!inFile.exists()){
return null;
}
Object o = null;
try {
ObjectInputStream in = new ObjectInputStream(
new BufferedInputStream(new FileInputStream(inFile)));
o = in.readObject();
in.close();
} catch (Exception e) {
System.out.println(e);
}
return o;
}
另外,
1、需要读写的对象需要实现序列化接口(
)
- xxxx implements Serializable
2、返回Object可以用instanceoff关键字判断是否是某一种对象,例如
if(object instanceof int[]){
System.out.println("length of the arr is : "+ ((int[])object).length);
}