Java读取ini文件

诸俊才
2023-12-01

Java读取ini文件


1. ini文件

src/config/config.ini文件内容如下:

[login]
autorun=n
jls=2
url=10.10.1.29
port=80
account=ufsoft

2. 代码示例

package com.accord.util;
 
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
 
/**
 * Java解析.ini文件
 * @author Administrator
 *
 */
public class ReadIniFile {
    public static void main(String[] args) throws Exception {
        ReadIniFile rf = new ReadIniFile();
        Map<String,String> map = rf.readFile();
        String port = map.get("port");
        String account = map.get("account");
        String url = map.get("url");
        System.out.println(port + ":" + account + ":" + url);
    }

    public Map<String,String> readIniFile() throws Exception {
        //读取src下面config包内的配置文件config.ini  
        InputStream in = ReadIniFile.class.getClassLoader().getResourceAsStream("config/config.ini"); 
        
        //也可以读取指定目录下的指定文件
        //InputStream in = new FileInputStream(new File("D:/config/config.ini"));
        BufferedReader br = new BufferedReader(new InputStreamReader(in));  
        Properties props = new Properties();  
        props.load(br);  
        Map<String, String> map = new HashMap<String, String>();
        for(Object s: props.keySet()){  
            //System.out.println(s+":"+props.getProperty(s.toString()));
            map.put(s.toString(), props.getProperty(s.toString()));
        } 
        //System.out.println(map.size());
        //String port = map.get("port");
        //System.out.println("port:" + port);
        return map;
    }
}
 类似资料: