在使用bukkit框架写插件的时候会经常使用到yml格式的文件来存储配置或者玩家数据,这里来说一下实现yml中数据的动态读写:

先来看一下yml文件中的内容结构

Bukkit之yaml动态读取-LMLPHP

 public boolean addBanSyntheseItem(CommandSender sender, Command cmd, String[] args) {
List list = new ArrayList<>();
Player player = (Player) sender;
ItemStack itemStack = player.getItemInHand();
File airdropFile = new File(Pickaxe.CONFIGPATH);
if(airdropFile.exists()) {
YamlConfiguration yc = new YamlConfiguration();
try {
yc.load(airdropFile);
} catch (Exception e) {
e.printStackTrace();
return false;
}
Set set = yc.getConfigurationSection("banItemList").getKeys(false);
int count = set.size();
//如果yml配置文件是空的,创建根节点,并且添加内容
if(count == 0) {
ConfigurationSection listSection = yc.createSection("banItemList");
Map<String, Object> item = new HashMap();
item.put("id",itemStack.getTypeId());
item.put("durability", (int)itemStack.getDurability());
item.put("type", itemStack.getType().toString());
item.put("displayName", itemStack.getItemMeta().getDisplayName());
item.put("lore", itemStack.getItemMeta().getLore());
listSection.createSection(Integer.toString(itemStack.getTypeId()),item);
try {
yc.save(Pickaxe.CONFIGPATH);
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}else if(count>0) { //如果yml中有内容,这直接在其后面追加内容
ConfigurationSection section = yc.getConfigurationSection("banItemList");
Map<String, Object> item = new HashMap();
item.put("id",itemStack.getTypeId());
item.put("durability", (int)itemStack.getDurability());
item.put("type", itemStack.getType().toString());
item.put("displayName", itemStack.getItemMeta().getDisplayName());
item.put("lore", itemStack.getItemMeta().getLore());
section.createSection(Integer.toString(itemStack.getTypeId()),item);
try {
yc.save(Pickaxe.CONFIGPATH);
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
}
return false; }
05-11 11:19