Solved Plugin Config To Single String

Discussion in 'Plugin Development' started by meguy26, Jul 3, 2015.

Thread Status:
Not open for further replies.
  1. Offline

    meguy26

    Okay, so I'm trying to write a method that converts any FileConfiguration into a single string, I've got most of it working, but I do not know how to do the spacing.

    Code as follows:
    Code:
        public static String configToSingleString(FileConfiguration config){
            return getAllInSection(config);
        }
       
        private static String getAllInSection(ConfigurationSection sec){
            StringBuilder sb = new StringBuilder();
            for(String s : sec.getKeys(false)){
                ConfigurationSection inner = sec.getConfigurationSection(s);
                if(inner != null){
                    sb.append(s).append(":").append("\n");
                    sb.append(getAllInSection(inner));
                } else {
                    sb.append(s).append(": ").append(sec.get(s)).append("\n");
                }
            }
            return sb.toString();
        }
    The above code on a config like the following:
    Code:
    Example:
        Ex:
            Ex4: true
        Ex2: 1
    returns:
    Code:
    Example:
    Ex:
    Ex4: true
    Ex2: 1
    So my question is, how do i retain the spacing...
     
  2. @meguy26
    Add an index parameter to getAllInSection and append x * 4 amount of spaces before the line. In configToSingleString you add argument 0 to the getAllInSection and when calling getAllInSection(inner) add parameter index + 1.
     
  3. Offline

    meguy26

    @megamichiel
    Like so?
    Code:
        public static String configToSingleString(FileConfiguration config){
            return getAllInSection(config, 0);
        }
      
        private static String getAllInSection(ConfigurationSection sec, int index){
            StringBuilder sb = new StringBuilder();
            for(String s : sec.getKeys(false)){
                ConfigurationSection inner = sec.getConfigurationSection(s);
                for(int i = 0; i < index; i++){
                    sb.append("    ");
                }
                if(inner != null){
                    sb.append(s).append(":").append("\n");
                    sb.append(getAllInSection(inner, index + 1));
                } else {
                    sb.append(s).append(": ").append(sec.get(s)).append("\n");
                }
            }
            return sb.toString();
        }
    I'm going to test it now...


    EDIT:
    Thanks! Looks like it worked. I tried something similar to this, but I was using a local variable and adding 1 in the wrong places, thank you so much!
     
Thread Status:
Not open for further replies.

Share This Page