温馨提示×

怎么用java的properties类读取配置文件

小亿
83
2023-12-14 00:02:34
栏目: 编程语言

要使用Java的Properties类来读取配置文件,需要按照以下步骤进行操作:

  1. 创建一个Properties对象:

    Properties prop = new Properties();
    
  2. 使用load()方法加载配置文件:

    FileInputStream input = new FileInputStream("config.properties");
    prop.load(input);
    
  3. 通过getProperty()方法获取配置项的值:

    String value = prop.getProperty("key");
    

完整的示例代码如下:

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

public class ConfigReader {
    public static void main(String[] args) {
        Properties prop = new Properties();

        try {
            FileInputStream input = new FileInputStream("config.properties");
            prop.load(input);
            
            // 读取配置项的值
            String value = prop.getProperty("key");
            System.out.println("Value: " + value);
            
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

需要注意的是,上述示例代码中的"config.properties"是指配置文件的路径,可以根据实际情况进行修改。另外,如果配置文件在类路径下,也可以使用getResourceAsStream()方法来加载配置文件,如下所示:

InputStream input = ConfigReader.class.getResourceAsStream("/config.properties");
prop.load(input);

0