温馨提示×

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

小亿
84
2023-12-26 19:10:14
栏目: 编程语言

在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()方法获取配置文件中的属性值。

0