【问题标题】:Get Array from YAML从 YAML 获取数组
【发布时间】:2015-10-14 22:43:59
【问题描述】:

我开发了一个 Minecraft Bukkit 插件,我想将信息保存在配置文件中。我想在我的 yaml 配置文件中保存一个数组并加载数据。这是我的 yaml 文件:

# Locations
Locations:
  - name: "Survival"
    position: 5
  - 
  - name: "PVP"
    position: 3

这是尝试加载数组的代码:

List<String> locations = config.getConfig().getStringList("Locations");
for(int i = 0; i < locations.size(); i++) {
    String[] location = locations.toArray(new String[0]);
    player.sendMessage("Name" + location[0] + ", Position" + location[1]);
}

但我没有收到聊天消息。如果我通过for 发送消息,我会收到一条消息。

【问题讨论】:

    标签: java snakeyaml


    【解决方案1】:

    你可以用这个:

    FileUtil.loadYamlFromResource("myLocationFile.yml", Location.class);
    
    Location.getLocation("location1").getSomething()
    

    并拥有这个 Location.class

    public class Location implements Serializable {
    
        private static final long serialVersionUID = -2360488391508732184L;
    
        private Map<String, Map<String, Double>> locations = new HashMap<>();
    
        public Float getLocation(String location) throws LocationNotFoundException {
                return locations.get(location);
        }
    
        /**
         * @return the locations 
         */
        public Map<String, Map<String, Double>> getLocations() {
            return locations ;
        }
    
        public void setLocations (Map<String, Map<String, Double>> locations ) {
            this.locations = locations ;
        }
    }
    

    在 FileUtil.class 中

    public static <T> T loadYamlFromResource(String resourcePath, Class<T> yamlClazz) {
    
        Yaml yaml = null;
    
        yaml = new Yaml(new CustomClassLoaderConstructor(yamlClazz.getClassLoader())); 
    
        InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(resourcePath);
    
        return yaml.loadAs(in, yamlClazz);
    }
    

    【讨论】:

      猜你喜欢
      • 2019-08-21
      • 1970-01-01
      • 2020-04-03
      • 1970-01-01
      • 2017-10-24
      • 1970-01-01
      • 2015-09-04
      • 2018-10-27
      • 2021-04-16
      相关资源
      最近更新 更多