Java

Java如何实现读取配置文件

小亿
99
2023-09-28 17:48:27
栏目: 编程语言

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

  1. 创建一个名为config.properties的配置文件,内容如下:
username=admin
password=123456
  1. 在Java代码中使用Properties类来读取配置文件:
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class ConfigReader {
public static void main(String[] args) {
Properties prop = new Properties();
FileInputStream input = null;
try {
input = new FileInputStream("config.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();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

运行以上代码,将会输出:

username: admin
password: 123456

以上代码使用Properties类的getProperty方法来获取配置文件中的属性值。配置文件需要位于Java代码所在的目录中,或者通过相对路径或绝对路径指定其位置。

0
看了该问题的人还看了