Java读取ini方法

第一接触ini配置文件,这里记录两种读取方式:

  1. 通过Properties读取ini文件
    这种方式网上使用的最多也最方便,不过读取顺序会有变化。
/**
     * 最简单的读取ini方法 但是读取的顺序会变化
     * 
     * @param file
     * @return
     * @throws Exception
     */
    public String read(String file) throws Exception {
        Properties pro = new Properties();
        StringBuffer sb = new StringBuffer();
        InputStream in = new BufferedInputStream(new FileInputStream(file));
        pro.load(in);
        Set keyValue = pro.keySet();
        for (Iterator it = keyValue.iterator(); it.hasNext();) {
            String key = (String) it.next();
            sb.append(key + ":" + pro.get(key) + "\n");
            // System.out.println(key + " "+ pro.get(key));
        }
        return sb.toString();
    }
  1. 自己写的读取方式,其中将ini注解变成#的方式输出,并根据ini每个节划分,组合“节_key”的方式输出。
private static HashMap<String, String> itemsMap = new HashMap<String, String>();
    private static String currentSection = "";//节名称

    /**
     * 读取ini 文件
     * @param file 文件路径
     * @return String 返回所有内容
     * @throws Exception
     */
    public String read2(String file) throws Exception {
        StringBuffer sb = new StringBuffer();
        BufferedReader bf = new BufferedReader(new InputStreamReader(
                new FileInputStream(file), "GB2312"));
        String line = null;
        while ((line = bf.readLine()) != null) {
            line = line.trim();

            if ("".equals(line))
                continue;
            if (line.startsWith("[") && line.endsWith("]")) {
                currentSection = line.substring(1, line.length() - 1);
                sb.append(currentSection+"\r\n");
            }else if(line.startsWith(";")){
                String str = "#"+line.substring(1);
                sb.append(str+"\r\n");
            }else {
                int index = line.indexOf("=");
                if (index != -1) {
                    String key = currentSection + "_"
                            + line.substring(0, index);
                    String value = line.substring(index + 1, line.length());
                    itemsMap.put(key, value);
                    sb.append(key+"="+value+"\r\n");
                }
            }
        }
        return sb.toString();
    }

暂时总结这一点点,后续用到在添加。

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值