文件/对象 输入输出
将对象写入文件:
- 创建对象
Studen stu=new Student(“tom”,12,”男”);
- 创建文件输出流:FileOutputStream
FileOutputStream fos = new FileOutputStream(“d:/test/student.bin”);
- 创建对象输出流: ObjectOutputStream
ObjectOutputStream oos = new ObjectOutputStream( fos);
- 写入对象: writeObject()
oos.writeObject(stu);
- 关闭流:close()
- oos.close();
注:注意文件路径是用d:/test/student.bin的形式,test文件夹需先创建好,student.bin不必
从文件读出对象:
- 创建文件输入流:FileInputStream
FileInputStream fis = new FileInputStream (“d:/test/student.bin”);
- 创建对象输入流: ObjectInputStream
ObjectInputStream ois = new ObjectInputStream (fis);
- 读出对象: readObject()
Student student=(Student) ois. readObject ();
- 关闭流:close()
- ois.close();
注:d:/test/student.bin已经存在的情况下
示例代码
Student.java
package entity;
import java.io.Serializable;
public class Student implements Serializable {
private String name;
private String gender;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
oiTest.java
package test;
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 entity.Student;
public class oiTest {
public static void main(String[] args) {
Student stu = new Student();
stu.setAge(12);
stu.setName("tom");
stu.setGender("男");
FileOutputStream fos=null;
FileInputStream fis=null;
ObjectOutputStream oos=null;
ObjectInputStream ois=null;
try {
//写出文件
fos = new FileOutputStream("d:/test/student.java");
//从文件中取出
fis=new FileInputStream("d:/test/student.java");
try {
oos=new ObjectOutputStream(fos);
ois=new ObjectInputStream(fis);
oos.writeObject(stu);
try {
Student s=(Student)ois.readObject();
System.out.println(s.getName());
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
ois.close();
oos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}