我的等級java項目具有以下結構。無法加載並從屬性文件中讀取
正如你所看到的資源文件夾存在於類路徑中。
但是,當我在一個類中運行下面的Java文件夾
new File("somefile.txt").exists()
下,我得到FileNotFoundException
。
任何人都可以幫助我找到爲什麼我無法訪問此文件。 這是在課程路徑中。
我的等級java項目具有以下結構。無法加載並從屬性文件中讀取
正如你所看到的資源文件夾存在於類路徑中。
但是,當我在一個類中運行下面的Java文件夾
new File("somefile.txt").exists()
下,我得到FileNotFoundException
。
任何人都可以幫助我找到爲什麼我無法訪問此文件。 這是在課程路徑中。
您可以使用。
ClassLoader classLoader = getClass().getClassLoader();
String filePath= classLoader.getResource("filename").getFile();
new File(filePath).exists();
欲瞭解更多信息,你可以通過this教程。
classLoader.getResource(「filename」)。getFile(); - 我昨天通過閱讀java文檔得到了這個,但是接受了你的答案。 – sreeprasad
乾杯,謝謝:) – mallaudin
可以解決像下面
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");
}
可能是你能給乾淨構建了一槍您的問題。刪除構建文件夾+無效intellij緩存+ gradle刷新(刪除舊的工件後)。 –