【文件属性】:
文件名称:java中的IO操作总结(四)
文件大小:116KB
文件格式:RAR
更新时间:2016-09-20 11:54:15
java IO
java中的IO操作总结(四)
前面已经把java io的主要操作讲完了
这一节我们来说说关于java io的其他内容
Serializable序列化
实例1:对象的序列化
?
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 import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
@SuppressWarnings("serial")
//一个类要想实现序列化则必须实现Serializable接口
class Person implements Serializable {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String toString() {
return "Name:" + this.name + ", Age:" + this.age;
}
}
public class Demo {
public static void main(String[] args) {
String path = File.separator + "home" + File.separator + "siu" +
File.separator + "work" + File.separator + "demo.txt";
Person p1 = new Person("zhangsan",12);
Person p2 = new Person("lisi",14);
//此处创建文件写入流的引用是要给ObjectOutputStream的构造函数玩儿
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try {
fos = new FileOutputStream(path);
oos = new ObjectOutputStream(fos);
//这里可以写入对象,也可以写入其他类型数据
oos.writeObject(p1);
oos.writeObject(p2);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
解压密码 www.jiangyea.com