本例以Windows, JDK1.7 为基础,来演示使用Java 将对象写入到文件。
Java 提供ObjectOutputStream类可以用于对对象的操作,这里使用writeObject(Object obj)方法。
注意:写入对象必须实现java.io.Serializable接口

写入对象到文件

对象
Student.java
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;
}


}
写入
FileObjectWrite.java
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
package com.devnp.io;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class FileObjectWrite {

public static void main(String[] args) {
// TODO Auto-generated method stub
Student student = new Student("Du Liu", 26);

writeObj(student);
}

public static void writeObj(Student student){

FileOutputStream fout = null;
ObjectOutputStream oos = null;

try {

fout = new FileOutputStream("D:\\Person-Test\\temp\\sudent.txt");
oos = new ObjectOutputStream(fout);
oos.writeObject(student);

System.out.println("Write " + student.getClass().getName() + " is Success.");

} catch (Exception ex) {

ex.printStackTrace();

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

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

}

异常

1. java.io.NotSerializableException

对象需要实现java.io.Serializable接口

参考

1. ObjectOutputStream