java怎么读取config目录下配置文件
要读取config目录下的配置文件,可以使用Java中的Properties类来实现。
首先,需要通过类加载器获取到配置文件的输入流。假设配置文件的名字是config.properties,可以使用以下代码获取到输入流:
InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("config/config.properties");
接下来,可以使用Properties类加载输入流,并读取配置文件中的内容:
Properties properties = new Properties();
properties.load(inputStream);
现在,配置文件中的内容已经加载到Properties对象中了。可以通过getProperty()方法来获取配置项的值:
String configValue = properties.getProperty("config.key");
其中,config.key是配置项的键值。
完整的代码示例:
import java.io.InputStream;
import java.util.Properties;
public class ConfigReader {
public static void main(String[] args) {
try {
// 获取配置文件的输入流
InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("config/config.properties");
// 加载配置文件
Properties properties = new Properties();
properties.load(inputStream);
// 读取配置项的值
String configValue = properties.getProperty("config.key");
System.out.println("配置项的值是:" + configValue);
// 关闭输入流
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
请确保配置文件config.properties位于config目录下,并且在类路径中可访问到。
版权声明
本文仅代表作者观点,不代表米安网络立场。
上一篇:美国服务器租用后要怎么维护 下一篇:租用页游服务器为什么选择高防服务器
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。