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

avatar
作者
筋斗云
阅读量:0

在Java中,可以使用Properties类来读取配置文件。以下是一个简单的示例:

  1. 创建一个配置文件config.properties,内容如下:
name=John age=25 
  1. 在Java代码中使用Properties类来读取配置文件:
import java.io.FileInputStream; import java.io.IOException; import java.util.Properties;  public class Main {     public static void main(String[] args) {         Properties properties = new Properties();         FileInputStream input = null;          try {             input = new FileInputStream("config.properties");             properties.load(input);              // 读取配置文件中的属性值             String name = properties.getProperty("name");             String age = properties.getProperty("age");              System.out.println("name: " + name);             System.out.println("age: " + age);          } catch (IOException e) {             e.printStackTrace();         } finally {             if (input != null) {                 try {                     input.close();                 } catch (IOException e) {                     e.printStackTrace();                 }             }         }     } } 

在上述代码中,首先创建了一个Properties对象,然后使用FileInputStream来加载配置文件。接下来,使用load()方法将配置文件加载到Properties对象中。最后,使用getProperty()方法获取配置文件中的属性值。

广告一刻

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