2016-11-19 43 views
2

我的等级java项目具有以下结构。无法加载并从属性文件中读取

正如你所看到的资源文件夹存在于类路径中。

但是,当我在一个类中运行下面的Java文件夹

new File("somefile.txt").exists() 

下,我得到FileNotFoundException

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

enter image description here

+0

可能是你能给干净构建了一枪您的问题。删除构建文件夹+无效intellij缓存+ gradle刷新(删除旧的工件后)。 –

回答

0

您可以使用。

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

欲了解更多信息,你可以通过this教程。

+0

classLoader.getResource(“filename”)。getFile(); - 我昨天通过阅读java文档得到了这个,但是接受了你的答案。 – sreeprasad

+0

干杯,谢谢:) – mallaudin

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