Search code examples
javafileyamlbukkit

Looping through multiple YAML files to find specific data


I would like to just ask, how would one be able to loop through YAML files to find the needed data?

My situation: I have a Spigot/Bukkit server, and it has a folder filled with lots of files. What I'd need to do, is go through each of these files separately in the plugin to find which file contains the data I need. How could I achieve this?


Solution

  • You can loop through Files by using:

    YamlConfiguration config = new YamlConfiguration();
    File[] files = this.getDataFolder().listFiles();
    for(File file : files){
        try {
            config.load(file);
            if(config.contains("Path")){
                //What you need to do.
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InvalidConfigurationException e) {
            e.printStackTrace();
        }
    }
    

    loading them and then cycling through loading them, and then checking if they contain the path you need. However, you may need to specify a folder, to do that simply do a statement within the for loop like:

    file = new File(file.getAbsolutePath() + File.separator + "FOLDER_NAME");
    

    But really that last part is incase you have other types of files. You can end up getting an exception if you aren't careful. In general what you are doing isn't generally necessary and there is most likely a much better solution. Just answering your question though.