将对象存入文件系统:
1.要存入的对象
import java.io.Serializable;
import java.util.*;
//要存入文件系统的对象须序列化(实现Serializable)
public class TestSerializable implements Serializable {
List list ;
public TestSerializable() {
list = new ArrayList();
setList();
}
public void setList(){
l.add("设备管理");
l.add("软件管理");
l.add("会议管理");
l.add("项目管理");
}
public List getList(){
return list;
}
}
2.读写对象
import java.io.FileOutputStream;
import java.io.*;
import java.util.*;
public class UntiTest {
TestSerializable ts;
public UntiTest() {
ts = new TestSerializable();
}
public void save(){//把对象写入文件系统
try {
FileOutputStream fos = new FileOutputStream("c:\\test.object");
ObjectOutputStream out = new ObjectOutputStream(fos);
out.writeObject(ts);
out.close();
}
catch (FileNotFoundException ex) {System.out.println(ex.getMessage());}
catch (IOException ex1) {System.out.println(ex1.getMessage());}
}
public void read(){//从文件系统读出对象
File file = new File("c:\\test.object");
if(file.exists()){
try {
FileInputStream fis = new FileInputStream(file);
ObjectInputStream in = new ObjectInputStream(fis);
TestSerializable ts = (TestSerializable) in.readObject();
List li = ts.getList();
Iterator it = li.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
catch (FileNotFoundException ex) {
System.out.println(ex.getMessage());
}
catch (IOException ex1) {
System.out.println(ex1.getMessage());
}
catch (ClassNotFoundException ex2) {
System.out.println(ex2.getMessage());
}
}else System.out.println("文件不存在");
}
public static void main(String[] args) {
UntiTest test = new UntiTest();
test.save();
test.read();
}
}
posted on 2006-04-06 15:44
Derek.Guo 阅读(284)
评论(0) 编辑 收藏 所属分类:
Java