您的位置:首页 > 其它

File.io读取文件(六)

2017-04-27 14:10 218 查看
import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

public class ObjectSerializeDemo {
public static void main(String[] args) {
String path="D:/aa.txt";
serialeTo(path);
seriale(path);
}

//反序列化
public static void seriale(String srcpath){
try(
ObjectInputStream bis=new ObjectInputStream(
new BufferedInputStream(
       new FileInputStream(
       
new File(srcpath))));
){
   Object obj=bis.readObject();
   Student st=null;
   if(obj instanceof Student){
    st=(Student)obj;
   }
//bis.close();
   System.out.println(st.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//序列化
public static void serialeTo(String destpath){
//创建数据源
Student st=new Student("杨幂",33);

File fos=new File(destpath);//无论保存什么格式类型的文件,都是乱码,这里
try(//jdk1.7,资源关闭新特性
ObjectOutputStream dos=new ObjectOutputStream(
new BufferedOutputStream(
new FileOutputStream(fos)));
){
dos.writeObject(st); 

dos.flush();//刷新管道数据
//dos.close();

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

}

//要实现对象反序列化/序列化必须实现Serializable接口

class Student implements java.io.Serializable{
private String name;
private  transient int age;//不需要序列化,就用transient修饰
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}

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