java实现Map解析器读取ini和MF文件



/**
 * map读取类,支持int和mf
 */
public class MapFileParser {

    private static final String TAG = MapFileParser.class.getSimpleName();

    private char mDividerChar = '=';

    private List<Entry> mEntries;

    private Map<String, Object> mEntryMap = new HashMap<>();

    private BufferedReader mReader;

    private BufferedWriter mWriter;

    private Writer mEditor;

    private File mFile;

    private String mCharsetName;


    public MapFileParser(InputStream in, String charsetName) throws UnsupportedEncodingException {
        mReader = new BufferedReader(new InputStreamReader(in, charsetName));
    }

    public MapFileParser(File file, String charsetName) throws FileNotFoundException, UnsupportedEncodingException {
        this(new FileInputStream(file), charsetName);
        this.mFile = file;
        this.mCharsetName = charsetName;
    }

    /**
     * 项目
     *
     * @param <T>
     */
    public static class Entry<T> {
        private String key;
        private T value;

        public Entry() {
        }

        public Entry(String key, T value) {
            this.key = key;
            this.value = value;
        }

        public String getKey() {
            return key;
        }

        public void setKey(String key) {
            this.key = key;
        }

        public T getValue() {
            return value;
        }

        public void setValue(T value) {
            this.value = value;
        }
    }

    public class Writer {

        public Writer put(String key, Object value) {
            try {
                mEntryMap.put(key, value);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return this;
        }

        public Writer put(Entry entry) {
            if (entry == null) {
                throw new RuntimeException("entry is null");
            }
            return put(entry.getKey(), entry.getValue());
        }

        public Writer remove(String key) {
            mEntryMap.remove(key);
            return this;
        }

        public Writer clear() {
            mEntryMap.clear();
            return this;
        }

        public void commit() throws IOException {
            if (mEntries == null) readAllEntries();
            mWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(mFile), mCharsetName));
            if (mEntryMap.isEmpty()) {
                mWriter.flush();
            } else {
                for (Map.Entry<String, Object> entry : mEntryMap.entrySet()) {
                    System.out.println(entry.getKey() + "," + String.valueOf(entry.getValue()));
                    mWriter.write(entry.getKey());
                    mWriter.write(mDividerChar);
                    mWriter.write(String.valueOf(entry.getValue()));
                    mWriter.newLine();
                }
                mWriter.flush();
            }
        }
    }

    /**
     * 读取下一个项目,字符串值
     *
     * @return
     * @throws IOException
     */
    public Entry<String> readEntryString() throws IOException {
        String line = mReader.readLine();
        if (line == null) {
            return null;
        }
        String data = line.trim();
        int pos = data.indexOf(mDividerChar);
        Entry<String> entry = new Entry<>();
        if (pos != -1) {
            entry.key = pos == 0 ? "" : data.substring(0, pos).trim();
            entry.value = pos == data.length() - 1 ? "" : data.substring(pos + 1).trim();
        }
        return entry;
    }

    /**
     * 读取下一个项目
     *
     * @return
     * @throws IOException
     */
    public Entry readEntry() throws IOException {
        Entry<String> rawEntry = readEntryString();
        if (rawEntry == null) return null;
        String value = rawEntry.value;
        Entry entry = new Entry();
        entry.setKey(rawEntry.getKey());
        if (value == null || value.isEmpty()) {
            entry.value = value;
        } else {
            boolean isString = value.startsWith("\"") && value.endsWith("\"");
            if (isString) {
                entry.value = value.substring(1, value.length() - 1);
            } else if (isNumber(value)) {
                if (value.contains(".")) {
                    if (value.length() <= 9) {
                        entry.value = Float.valueOf(value);
                    } else {
                        try {
                            entry.value = Double.parseDouble(value);
                        } catch (Exception e) {
                            entry.value = value;
                        }
                    }
                } else {
                    try {
                        long lngVal = Long.parseLong(value);
                        if (lngVal >= Integer.MIN_VALUE && lngVal <= Integer.MAX_VALUE) {
                            entry.value = (int) lngVal;
                        } else {
                            entry.value = lngVal;
                        }
                    } catch (Exception e) {
                        entry.value = value;
                    }
                }
            } else if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("false")) {
                entry.value = Boolean.valueOf(value);
            } else {
                entry.value = value;
            }
        }
        return entry;
    }

    /**
     * 读取所有项目
     *
     * @throws IOException
     */
    public void readAllEntries() throws IOException {
        mReader.mark(0);
        mReader.reset();
        List<Entry> entries = new ArrayList<>();
        while (true) {
            Entry entry = readEntry();
            if (entry == null) break;
            if (entry.getKey() == null || entry.getKey().isEmpty()) continue;
            entries.add(entry);
        }
        mEntries = entries;
        mEntryMap.clear();
        for (Entry entry : mEntries) {
            mEntryMap.put(entry.getKey(), entry.getValue());
        }
    }

    /**
     * 读取所有项目字符串格式
     *
     * @return Map<String, String>
     * @throws IOException
     */
    public Map<String, String> readAllEntriesString() throws IOException {
        mReader.mark(0);
        mReader.reset();
        Map<String, String> map = new HashMap<>();
        while (true) {
            Entry<String> entry = readEntryString();
            if (entry == null) break;
            if (entry.getKey() == null || entry.getKey().isEmpty()) continue;
            map.put(entry.getKey(), entry.getValue());
        }
        return map;
    }

    /**
     * 获取所有项目列表
     *
     * @return List
     */
    public List<Entry> getEntries() {
        if (mEntries == null) {
            try {
                readAllEntries();
            } catch (Exception e) {
                println(TAG, e.toString());
            }
        }
        return mEntries;
    }

    /**
     * 获取所有项目映射
     *
     * @return
     */
    public Map<String, ?> getEntryMap() {
        return mEntryMap;
    }

    /**
     * 获取项目个数
     *
     * @return
     */
    public int getEntryCount() {
        return mEntries == null ? 0 : mEntries.size();
    }

    public Object get(String key) {
        return mEntryMap.get(key);
    }

    public int getInt(String key, int defValue) {
        Object value = get(key);
        if (value instanceof Integer) {
            return (Integer) value;
        } else {
            try {
                return Integer.valueOf(String.valueOf(value));
            } catch (Exception e) {
                return defValue;
            }
        }
    }

    public Integer getInteger(String key) {
        Object value = get(key);
        if (value instanceof Integer) {
            return (Integer) value;
        } else {
            try {
                return Integer.valueOf(String.valueOf(value));
            } catch (Exception e) {
                return null;
            }
        }
    }

    public String getString(String key) {
        Object value = get(key);
        if (value instanceof String) {
            return (String) value;
        } else {
            return value == null ? null : String.valueOf(value);
        }
    }

    public long getLong(String key, long defValue) {
        Object value = get(key);
        if (value instanceof Long) {
            return (Long) value;
        } else {
            try {
                return Long.valueOf(String.valueOf(value));
            } catch (Exception e) {
                return defValue;
            }
        }
    }

    public boolean getBoolean(String key, boolean defValue) {
        Object value = get(key);
        if (value instanceof Boolean) {
            return (Boolean) value;
        } else {
            try {
                return Boolean.valueOf(String.valueOf(value));
            } catch (Exception e) {
                return defValue;
            }
        }
    }

    public float getFloat(String key, float defValue) {
        Object value = get(key);
        if (value instanceof Float) {
            return (Float) value;
        } else {
            try {
                return Float.valueOf(String.valueOf(value));
            } catch (Exception e) {
                return defValue;
            }
        }
    }

    public boolean hasKey(String key) {
        return mEntryMap.containsKey(key);
    }

    public Entry getEntry(int index) {
        if (mEntries == null) {
            return null;
        }
        return mEntries.get(index);
    }

    public void setDividerChar(char mDividerChar) {
        if (mDividerChar == 0) throw new RuntimeException("divider not is null");
        this.mDividerChar = mDividerChar;
    }

    private static boolean isNumber(CharSequence str) {
        final int len = str.length();
        int dotCount = 0;
        for (int cp, i = 0; i < len; i += Character.charCount(cp)) {
            cp = Character.codePointAt(str, i);
            if (cp == '.') dotCount++;
            if (!(Character.isDigit(cp) || cp == '.' && dotCount == 1)) {
                return false;
            }
        }
        return true;
    }

    private static void println(Object... args) {
        if (args != null) {
            for (Object arg : args) {
                System.out.print(arg + ", ");
            }
            System.out.println();
        }
    }

    public void setFileType(Type type) {
        if (type == Type.Ini) {
            setDividerChar('=');
        } else if (type == Type.Manifest) {
            setDividerChar(':');
        }
    }

    public Writer writer() {
        if (mEditor == null) {
            mEditor = new Writer();
        }
        return mEditor;
    }

    public void close() {
        try {
            if (mWriter != null) {
                mWriter.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            if (mReader != null) {
                mReader.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public enum Type {
        Ini,
        Manifest
    }
}

Guess you like

Origin blog.csdn.net/zzmzzff/article/details/130757590