温馨提示×

java怎么获取配置文件参数

小亿
105
2023-09-28 17:28:34
栏目: 编程语言

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

首先,创建一个名为config.properties的配置文件,并在文件中添加以下内容:

name=John Doe
age=30

然后,在Java代码中使用Properties类读取配置文件中的参数:

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class ConfigReader {
public static void main(String[] args) {
Properties properties = new Properties();
FileInputStream configFile = null;
try {
configFile = new FileInputStream("config.properties");
properties.load(configFile);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (configFile != null) {
try {
configFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
String name = properties.getProperty("name");
int age = Integer.parseInt(properties.getProperty("age"));
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}

运行上述代码,将输出以下结果:

Name: John Doe
Age: 30

上述代码中,首先创建了一个Properties对象properties,然后使用FileInputStream来读取配置文件config.properties。接着,使用properties.load(configFile)方法加载配置文件中的参数。最后,使用getProperty方法根据参数名获取相应的值。使用Integer.parseInt将字符串类型的年龄转换为整数类型。

注意:在使用FileInputStream读取配置文件时,需要提供配置文件的路径。上述示例假设配置文件与Java代码位于同一目录下,如果不是,请提供正确的路径。

0