流写对象的使用方法
public class Filefir {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
writerMothod();
}
//读
public static void readerMothod() throws IOException, ClassNotFoundException {
File file= new File("E:/object.txt");
InputStream is = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(is);
//Object object = ois.readObject();
try {
Object obj = null;
if((obj= ois.readObject())!=null) {
System.out.println(obj);
}
} catch (Exception e) {
System.out.println("读取完毕");
// TODO: handle exception
}
/*
* Object object = ois.readObject();
* Item item = (Item) object;
* System.out.println(item);
*/
ois.close();
is.close();
}
**//写入**
public static void writerMothod() throws IOException {
//指入写入的地址
File file= new File("E:/object.txt");
//创建写对象的对象流
OutputStream os = new FileOutputStream(file);
//创建要存储的对象
ObjectOutputStream oos = new ObjectOutputStream(os );
Item item = new Item("李磊", 19, "男");
Item item2 = new Item("李阳", 20, "女");
oos.writeObject(item);
oos.writeObject(item2);
//从后往前关闭
oos.close();
os.close();
}
}
//实体类
//继承Serializable接口
public class Item implements Serializable{
private String name;
private int age;
private String sex;
public Item(String name, int age, String sex) {
super();
this.name = name;
this.age = age;
this.sex = sex;
}
public Item() {
super();
}
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;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return “Item [name=” + name + “, age=” + age + “, sex=” + sex + “]”;
}
}