无法加载和读取属性文件

时间:2016-11-19 21:17:31

标签: gradle

我的成绩java项目具有以下结构。

如您所见,资源文件夹位于类路径中。

但是当我在java文件夹

下的类中运行以下内容时
new File("somefile.txt").exists() 

我得到FileNotFoundException

任何人都可以帮我找到为什么我无法访问此文件。 这是在类路径中。

enter image description here

2 个答案:

答案 0 :(得分:0)

你可以使用。

ClassLoader classLoader = getClass().getClassLoader();
String filePath= classLoader.getResource("filename").getFile();
new File(filePath).exists();

有关详情,请参阅enter image description here教程。

答案 1 :(得分:0)

您可以解决以下问题

Properties prop = new Properties();          
InputStream inputStream = getClass().getClassLoader().getResourceAsStream("somefile.txt"); 
if (inputStream != null) {
    prop.load(inputStream);
} else {
    throw new FileNotFoundException("Property file '" + fileName + "' not found in the classpath");
}

我是从帖子How to read properties file in Java

中找到的