您的位置:首页 > 编程语言 > Java开发

Java 持久化操作之 --io流与序列化

2018-04-06 20:14 459 查看

1)File类操作文件的属性

1.File类的常用方法

package text;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class TextStudent {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
//创建序列化对象
ObjectOutputStream xl=null;
//创建反序列化对象
ObjectInputStream xl1=null;
//初始化要序列化的对象
Map<String,Student> map=new HashMap<String,Student>();
Map<String,Student> map1=new HashMap<String,Student>();
Student stu=new Student("小明",18,"男");
Student stu1=new Student("小红",18,"女");
map.put(stu.getName(), stu);
map.put(stu1.getName(), stu1);
try {
xl=new ObjectOutputStream(new FileOutputStream("D://TextFile//xuliehua.bin"));
xl1=new ObjectInputStream(new FileInputStream("D://TextFile//xuliehua.bin"));
xl.writeObject(map);
System.out.println("写入成功");
//反序列化文件输出到控制台
map1=(Map<String,Student>)xl1.readObject();
Set<String> key=map1.keySet();
Iterator<String> l=key.iterator();
while(l.hasNext())
{
String keys=l.next();
map1.get(keys).show();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
if(xl!=null){
try {
xl.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(xl1!=null)
{
try {
xl1.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

}
}
测试类 提示:如果不希望Student类某一属性被序列化可使用 transient 修饰

 

 biu ~biu ~ biu ~  

注:最后在提一句:使用序列化操作时,一定要将准备序列化的类或数据声明为可序列化操作!!!!

 

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