在模型中添加保存和加载元素的代码,将数组adress中元素保存到Adress.xml文件
而数据的保存在Activator的stop方法中,插件退出时保存数据
[img]http://dl.iteye.com/upload/attachment/159322/64cb4440-fdb6-3552-b572-7a5093d85ec3.jpg[/img]
由于包含中文,要在浏览器或编辑器中正确显示xml文档,需要将xml的编码方式从UTF-8改成gb2312
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