视图开发-数据保存

在模型中添加保存和加载元素的代码,将数组adress中元素保存到Adress.xml文件

public class AddressManager implements IPropertyChangeListener{
private static final String TAG_ADDRESSES = "Addresses";
private static final String TAG_ADDRESS = "AddressItem";
private static final String TAG_NAME = "name";
private static final String TAG_CATEGORY = "category";

public void saveAddresses(){
if(addresses == null)
return;
XMLMemento memento = XMLMemento.createWriteRoot(TAG_ADDRESSES);
saveAddresses(memento);
FileWriter writer = null;
try{
writer = new FileWriter(getAddressesFile());
memento.save(writer);
}catch(IOException e){
//to be added
}finally{
try{
if(writer != null)
writer.close();
}catch(IOException e){
//to be added
}
}
}
public void saveAddresses(IMemento memento){
Iterator iter = addresses.iterator();
while(iter.hasNext()){
AddressItem item = (AddressItem)iter.next();

IMemento child = memento.createChild(TAG_ADDRESS);
child.putString(TAG_NAME, item.getName());
child.putString(TAG_CATEGORY, item.getCategory().getCategoryName());
}
}

private File getAddressesFile() {
IPath path=Activator.getDefault().getStateLocation();
return
path.append("Addresses.xml").toFile();
}


//从文件读取元素

private void loadAddresses(){
FileReader reader = null;
try{
reader = new FileReader(getAddressesFile());
loadAddresses(XMLMemento.createReadRoot(reader));
}catch(FileNotFoundException e)
{
//to be added
}catch(Exception e)
{
//to be added
}finally{
try{
if(reader != null)
reader.close();
}
catch(IOException e){
//to be added
}
}
/*end*/
}
private void loadAddresses(XMLMemento memento)
{
IMemento[] children = memento.getChildren(TAG_ADDRESS);
for(int i = 0; i < children.length; i++)
{
AddressItem item = createNewAddressItem(children[i].getString(TAG_NAME),
children[i].getString(TAG_CATEGORY));
if(item != null)
addresses.add(item);
}
}

public AddressItem createNewAddressItem(String name, String categoryName) {
AddressCategory category = AddressCategory.getCategoryMap().get(categoryName);
return new AddressItem(name, category);
}
}

//显示之前,先加载
public AddressItem[] getAddresses(){
if(addresses == null)
loadAddresses();
return (AddressItem[])addresses.toArray(
new AddressItem[addresses.size()]);
}


而数据的保存在Activator的stop方法中,插件退出时保存数据

public void stop(BundleContext context) throws Exception {
AddressManager.getManager().saveAddresses();
plugin = null;
super.stop(context);
}


[img]http://dl.iteye.com/upload/attachment/159322/64cb4440-fdb6-3552-b572-7a5093d85ec3.jpg[/img]
由于包含中文,要在浏览器或编辑器中正确显示xml文档,需要将xml的编码方式从UTF-8改成gb2312
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值