Pulling values from a Java Properties file in order?

前端 未结 15 764
庸人自扰
庸人自扰 2020-12-02 18:32

I have a properties file where the order of the values is important. I want to be able to iterate through the properties file and output the values based on the order of the

15条回答
  •  南笙
    南笙 (楼主)
    2020-12-02 19:27

    I'll add one more famous YAEOOJP (Yet Another Example Of Ordered Java Properties) to this thread because it seems nobody could ever care less about default properties which you can feed to your properties.

    @see http://docs.oracle.com/javase/tutorial/essential/environment/properties.html

    That's my class: surely not 1016% compliant with any possible situation, but that is fine for my limited dumb purposes right now. Any further comment for correction is appreciated so the Greater Good can benefit.

    import java.util.Collections;
    import java.util.Enumeration;
    import java.util.LinkedHashSet;
    import java.util.Map;
    import java.util.Properties;
    import java.util.Set;
    
    /**
     * Remember javadocs  >:o
     */
    public class LinkedProperties extends Properties {
    
        protected LinkedProperties linkedDefaults;
        protected Set linkedKeys = new LinkedHashSet<>();
    
        public LinkedProperties() { super(); }
    
        public LinkedProperties(LinkedProperties defaultProps) {
            super(defaultProps); // super.defaults = defaultProps;
            this.linkedDefaults = defaultProps;
        }
    
        @Override
        public synchronized Enumeration propertyNames() {
            return keys();
        }
    
        @Override
        public Enumeration keys() {
            Set allKeys = new LinkedHashSet<>();
            if (null != defaults) {
                allKeys.addAll(linkedDefaults.linkedKeys);
            }
            allKeys.addAll(this.linkedKeys);
            return Collections.enumeration(allKeys);
        }
    
        @Override
        public synchronized Object put(Object key, Object value) {
            linkedKeys.add(key);
            return super.put(key, value);
        }
    
        @Override
        public synchronized Object remove(Object key) {
            linkedKeys.remove(key);
            return super.remove(key);
        }
    
        @Override
        public synchronized void putAll(Map values) {
            for (Object key : values.keySet()) {
                linkedKeys.add(key);
            }
            super.putAll(values);
        }
    
        @Override
        public synchronized void clear() {
            super.clear();
            linkedKeys.clear();
        }
    
        private static final long serialVersionUID = 0xC00L;
    }
    
    
    
        

    提交回复
    热议问题