java中怎么用properties类读取配置文件
在Java中,可以使用Properties类来读取配置文件。以下是一个简单的示例:
- 创建一个配置文件
config.properties,内容如下:
name=John
age=25
- 在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()方法获取配置文件中的属性值。
版权声明
本文仅代表作者观点,不代表米安网络立场。
博豪信息



发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。