本例以Windows, JDK1.7 为基础,来演示使用Java 从文件中读取对象。
Java 提供ObjectInputStream类可以用于对对象的操作,这里使用readObject()方法。

注意:对象必须实现java.io.Serializable接口

读取对象

Student对象
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package com.devnp.io;

import java.io.Serializable;

public class Student implements Serializable{

/**
*
*/
private static final long serialVersionUID = 1L;

private String name ;

private Integer age ;


public Student() {
super();
}

public Student(String name, Integer age) {
super();
this.name = name;
this.age = age;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Integer getAge() {
return age;
}

public void setAge(Integer age) {
this.age = age;
}


}
读取对象
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package com.devnp.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

public class FileObjectRead {

public static void main(String[] args) {
// TODO Auto-generated method stub
Student student = readObj(new File("D:\\Person-Test\\temp\\sudent.txt"));

System.out.println("Sudent Name : " + student.getName() + ", Age : " + student.getAge());
}

public static Student readObj(File file) {
FileInputStream fin = null;
ObjectInputStream ois = null;

Student student = null;
try {

fin = new FileInputStream(file);
ois = new ObjectInputStream(fin);
student = (Student) ois.readObject();

} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (fin != null)
fin.close();
} catch (IOException e) {
e.printStackTrace();
}

try {
if (ois != null)
ois.close();
} catch (IOException e) {
e.printStackTrace();
}

}

return student;

}

}
运行结果
1
Sudent Name : Du Liu, Age : 26

相关

关于写入对象到文件可以参阅 Java File Write an Object 将对象写入到文件

参考

ObjectInputStream