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

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

Bukkit之yaml动态读取-冯金伟博客园

 1 public boolean addBanSyntheseItem(CommandSender sender, Command cmd, String[] args) {
 2         List list = new ArrayList<>();
 3         Player player = (Player) sender;
 4         ItemStack itemStack = player.getItemInHand();
 5         File airdropFile = new File(Pickaxe.CONFIGPATH);
 6         if(airdropFile.exists()) {
 7             YamlConfiguration yc = new YamlConfiguration();
 8             try {
 9                 yc.load(airdropFile);
10             } catch (Exception e) {
11                 e.printStackTrace();
12                 return false;
13             }
14             Set set = yc.getConfigurationSection("banItemList").getKeys(false);
15             int count = set.size();
16             //如果yml配置文件是空的,创建根节点,并且添加内容
17             if(count == 0) {
18                 ConfigurationSection listSection = yc.createSection("banItemList");
19                  Map<String, Object> item = new HashMap();
20                  item.put("id",itemStack.getTypeId());
21                  item.put("durability", (int)itemStack.getDurability());
22                  item.put("type", itemStack.getType().toString());
23                  item.put("displayName", itemStack.getItemMeta().getDisplayName());
24                  item.put("lore", itemStack.getItemMeta().getLore());
25                  listSection.createSection(Integer.toString(itemStack.getTypeId()),item); 
26                  try {
27                     yc.save(Pickaxe.CONFIGPATH);
28                     return true;
29                 } catch (IOException e) {
30                     e.printStackTrace();
31                     return false;
32                 }
33             }else if(count>0) {    //如果yml中有内容,这直接在其后面追加内容
34                 ConfigurationSection section = yc.getConfigurationSection("banItemList");
35                  Map<String, Object> item = new HashMap();
36                 item.put("id",itemStack.getTypeId());
37                 item.put("durability", (int)itemStack.getDurability());
38                 item.put("type", itemStack.getType().toString());
39                 item.put("displayName", itemStack.getItemMeta().getDisplayName());
40                 item.put("lore", itemStack.getItemMeta().getLore());
41                 section.createSection(Integer.toString(itemStack.getTypeId()),item);
42                 try {
43                     yc.save(Pickaxe.CONFIGPATH);
44                     return true;
45                 } catch (IOException e) {
46                     e.printStackTrace();
47                     return false;
48                 }
49             }
50         }
51         return false;
52         
53     }