All Downloads are FREE. Search and download functionalities are using the official Maven repository.

top.bluesword.util.io.OrderedProperties Maven / Gradle / Ivy

The newest version!
package top.bluesword.util.io;

import top.bluesword.util.exception.SwordRuntimeException;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * @author 李林峰
 * 顺序读取properties配置文件
 */
public class OrderedProperties extends LinkedHashMap {

    private List keys = new ArrayList<>();

    private OrderedProperties() {
    }

    /**
     * 以指定编码格式将输入流按行置入一个List
     */
    private static List toLines(InputStream input) {
        try {
            InputStreamReader reader = new InputStreamReader(input, StandardCharsets.UTF_8);
            BufferedReader bin = new BufferedReader(reader);
            List lines = new ArrayList<>();
            String line;
            while ((line = bin.readLine()) != null) {
                lines.add(line);
            }
            return lines;
        } catch (IOException e) {
            throw new SwordRuntimeException();
        }
    }

    public String getProperty(String key) {
        return this.get(key);
    }

    /**
     * 加载Properties文件
     * @param inputStream Properties文件输入流
     */
    public synchronized void load(InputStream inputStream) {
        List lines = toLines(inputStream);
        for (String l : lines) {
            if (l.trim().startsWith("#")) {
                keys.add(l);
            } else {
                int indexOf = l.indexOf('=');
                if (indexOf > -1) {
                    String k = l.substring(0, indexOf).trim();
                    String v = l.substring(indexOf + 1).trim();
                    keys.add(k);
                    this.put(k, v);
                } else {
                    keys.add(l);
                }
            }
        }
    }

    public List getKeys() {
        return keys;
    }

    @Override
    public boolean equals(Object o) {
        if (!(o instanceof OrderedProperties)) return false;
        return super.equals(o);
    }

    @Override
    public int hashCode() {
        return super.hashCode();
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy