出于某种原因,我必须将我的 *.properties
文件放在 java 应用程序之外。当文件 km.properties
位于 java/src/resources/km.properties
中时,代码会读取该文件,但是当我将相同的文件放入 C:\用户\abc\桌面\km.properties
它抛出
Exception: java.io.FileNotFoundException: property file 'C:\Users\abc\Desktop\km.properties' not found in the classpath
Exception in thread "main" java.lang.NullPointerException
at com.ir.Constants.<init>(Constants.java:44)
at com.Constants.main(Constants.java:64)
这是我的代码
public class Constants {
public Constants(){
System.out.println(System.getenv("km_config"));
try {
Properties prop = new Properties();
String propFileName = System.getenv("km_config");
inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);
if (inputStream != null) {
prop.load(inputStream);
} else {
throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath");
}
}
catch (IOException e) {
System.out.println("Exception: " + e);
}
catch (Exception e) {
System.out.println("Exception: " + e);
} finally {
try {
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) throws Exception {
Constants c = new Constants();
System.out.println(Constants.DB_PATH1);
System.out.println(Constants.GIT_REPO_PATH);
System.out.println(Constants.GIT_MAIN_BRANCH_NAME);
System.out.println(Constants.TAGGER_PATH);
}
Constants.java:44
是
inputStream.close();
Constants.java:64
是
常量 c = new Constants();
请帮助我,我需要将 km.properies
文件放置在 java 应用程序之外的任何位置
命令结果为
echo %km_config%
C:\Users\abc\Desktop\km.properties
最佳答案
API ClassLoader::getResourceAsStream(String)
有一个搜索路径,即类路径。实际上,配置文件不应该与 .class 文件捆绑在一起,而是从目标计算机的文件系统中读取,你是对的。
因此您的 API 调用将变为:
Properties conf = new Properties();
conf.load(new InputStreamReader(new FileInputStream(new File(file)));
注意:我没有指定用于将字节流转换为字符流的字符集,因为我希望 JVM 选择系统默认的任何字符。
对于测试,我建议您:
- 将配置文件放在源(桌面)之外的已知位置,或者无论如何都会被版本控制系统忽略
- 将该值作为系统属性传递(例如
-Dfile=C:\Users\me\Desktop\km.properties
)
关于java - 属性文件驻留在 java 应用程序之外会抛出 fFileNotFoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51047295/