以下是一个简单的Java程序,可以读取配置文件并将其放入Map中:

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.HashMap;
import java.util.Map;

public class ConfigReader {

    private static final String FILENAME = "config.properties";

    public static void main(String[] args) {
        Map<String, String> configMap = readConfigFile();
        System.out.println("Config file contents:");
        for (Map.Entry<String, String> entry : configMap.entrySet()) {
            System.out.println(entry.getKey() + " = " + entry.getValue());
        }
    }

    public static Map<String, String> readConfigFile() {
        Map<String, String> configMap = new HashMap<>();
        try (BufferedReader br = new BufferedReader(new FileReader(FILENAME))) {
            String line;
            while ((line = br.readLine()) != null) {
                if (line.trim().startsWith("#") || line.trim().isEmpty()) {
                    continue;
                }
                String[] keyValue = line.split("=", 2);
                if (keyValue.length != 2) {
                    continue;
                }
                String key = keyValue[0].trim();
                String value = keyValue[1].trim();
                configMap.put(key, value);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return configMap;
    }
}

在这个例子中,我们假设配置文件的名称为“config.properties”。我们使用一个Map来存储配置文件中的键值对,其中键是配置项的名称,值是配置项的值。

在readConfigFile()方法中,我们使用BufferedReader从文件中读取每一行。我们跳过以“#”开头的注释行和空行。对于每一行,我们使用“=”标记分割键和值,并将它们放入Map中。最后,我们返回Map以供其他代码使用。

在main()方法中,我们简单地读取配置文件并将其内容打印到控制台上。您可以根据需要修改此代码以实现您的特定用例

帮我写一个java读取配置文件并放到map里的例子

原文地址: http://www.cveoy.top/t/topic/fsLT 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录