java读取properties配置文件的方法

在Java中,读取properties配置文件可以使用以下步骤:

  1. 创建一个Properties对象并导入该配置文件。
Properties prop = new Properties();
InputStream input = new FileInputStream("config.properties");
prop.load(input);
  1. 通过getProperty方法获取配置文件中的属性值。
String value = prop.getProperty("key");
  1. 关闭输入流。
input.close();

完整的代码示例如下:

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

public class ReadPropertyFile {
    public static void main(String[] args) {
        try (InputStream input = new FileInputStream("config.properties")) {
            Properties prop = new Properties();
            prop.load(input);

            String username = prop.getProperty("username");
            String password = prop.getProperty("password");

            System.out.println("Username: " + username);
            System.out.println("Password: " + password);

        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

其中,config.properties 是配置文件名,usernamepassword 是配置文件中的属性。执行以上代码将会输出配置文件中的 usernamepassword 属性值。

未经允许不得转载:国外服务器评测 » java读取properties配置文件的方法