无影无踪

BlogJava 首页 新随笔 联系 聚合 管理
  0 Posts :: 3 Stories :: 0 Comments :: 0 Trackbacks
在插件项目开发的时候,比如说不仅仅只是存储字符串,数字之类的变量,而是要存储任意一个对象。这时可以用序列化技术来实现。
    1)下面的例子序列化一个ArrayList,用这个ArrayList类的对象来存储和加载信息。
import java.util.ArrayList;
public class FileList extends ArrayList implements java.io.Serializable {
    public FileList() {
        super();
    }
}
说明:
一个类要能够实现序列化必须实现java.io.Serializable接口
2)下面来进行测试,首先生成一个FileList的对象
fileProfileList = new FileList();
3)序列化存储对象

void saveProfile() {
        try {
              File file = new File(path + "profile.save");
              file.createNewFile();

              // 获取文件的字节流对象
              ObjectOutputStream outer = new ObjectOutputStream(
                      new FileOutputStream(file));

              // 将save对象写入
              outer.writeObject(fileProfileList);
              outer.flush();
              outer.close();
        } catch (Exception e) {
              e.printStackTrace();
        }
    }

说明:String path = TauPlugin.getDefault().getStateLocation()
              .makeAbsolute().toOSString();
path为一个全局变量,指向保存该plugin的状态信息的位置,一般在$workspace/ .metadata/.plugins/$your_test_plugin目录下
4)序列化读取对象
private FileList loadProfile() {
        try {
              // 获取文件对象

              File f = new File(path + "profile.save");
              ObjectInputStream in = new ObjectInputStream(new FileInputStream(f));
              // 将文件对象中的字节流读出来,并保存在内存中的mySet对象中
              FileList list = (FileList) in.readObject();
              in.close();

              return list;
        } catch (Exception e) {
              e.printStackTrace();
        }
        return null;

    }
posted on 2006-08-07 23:25 eclipsetolearn 阅读(191) 评论(0)  编辑  收藏

只有注册用户登录后才能发表评论。


网站导航: