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

avatar
作者
筋斗云
阅读量:0

要使用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); 

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!