Bukkit编程之动态向yml文件中添加属性

2023-06-25,,

 yaml = new Yaml();
String goods = args[0];
String goodsNum = args[1]; YamlConfiguration yc = new YamlConfiguration();
try {
yc.load(new File(System.getProperty("user.dir")+"/plugins/PbMainPlugin/configDef.yml"));
} catch (FileNotFoundException e1) { e1.printStackTrace();
} catch (IOException e1) { e1.printStackTrace();
} catch (InvalidConfigurationException e1) { e1.printStackTrace();
} Set set = yc.getConfigurationSection("drop").getKeys(false); lastDropNum = set.size(); //查看yml文件中是否有内容,没有内容返回0,否则返回内容长度 player.sendMessage("大小是:"+set.size()+"");
player.sendMessage("内容是:"+set+"");
YamlConfiguration yamlConfiguration = new YamlConfiguration();
if(lastDropNum==0) { //如果原来yml文件中没有内容 ConfigurationSection drop = yamlConfiguration.createSection("drop"); Map<String, Object> item = new HashMap();
item.put("item-Id", Material.valueOf(goods.trim()).getId());
item.put("item-Name", Material.valueOf(goods.trim()).name());
drop.createSection("1",item);
try { yamlConfiguration.save(System.getProperty("user.dir")+"/plugins/PbMainPlugin/configDef.yml");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} } if(lastDropNum!=0) { //如果yml中有内容,则向yml文件中追加新的内容
yamlConfiguration = YamlConfiguration.loadConfiguration(new File(System.getProperty("user.dir")+"/plugins/PbMainPlugin/configDef.yml"));
ConfigurationSection drop = yamlConfiguration.getConfigurationSection("drop");
Map<String, Object> item = new HashMap();
item.put("item-Id", Material.valueOf(goods.trim()).getId());
item.put("item-Name", Material.valueOf(goods.trim()).name());
drop.set((lastDropNum+1)+"", item);
try {
yamlConfiguration.save(System.getProperty("user.dir")+"/plugins/PbMainPlugin/configDef.yml");
} catch (IOException e) { e.printStackTrace();
} } //向玩家背包中添加物品
PlayerInventory inventory = player.getInventory();
ItemStack itemStack = new ItemStack(Material.valueOf(goods.trim()),Integer.parseInt(goodsNum));
inventory.addItem(itemStack);
return true;

yml文件中的结构为:

Bukkit编程之动态向yml文件中添加属性的相关教程结束。

《Bukkit编程之动态向yml文件中添加属性.doc》

下载本文的Word格式文档,以方便收藏与打印。