首页 > 解决方案 > 无法从资源文件夹中读取文件

问题描述

最终编辑:现在代码看起来像这样

InputStream is = getClass().getResourceAsStream("/static/master-key.txt");
String masterKey = null;
Scanner scanner = new Scanner(is);
masterKey = scanner.nextLine();
System.out.println("the master key is " + masterKey);

原帖

resources从文件夹中读取 txt 文件时出现问题。

这是项目结构的样子:
projStructure

当我调用以下代码时

System.out.println(getClass().getClassLoader().getResource("static/master-key.txt").getPath());
File mkFile = new File(getClass().getClassLoader().getResource("static/master-key.txt").getPath());

这会发生什么

/D:/Dropbox/Coding/Intellij%20IDEA/TishenkoKPO/target/classes/static/master-key.txt
java.io.FileNotFoundException: 
D:\Dropbox\Coding\Intellij%20IDEA\TishenkoKPO\target\classes\static\master-key.txt (System cannot find the specified path)

我用谷歌搜索了很多,但不知道为什么会发生这种情况

编辑 1:按照社区建议重建的部分代码(使用文件作为资源)

InputStream is = getClass().getResourceAsStream("static/master-key.txt");
String masterKey = null;
Scanner scanner = new Scanner(is);
masterKey = scanner.nextLine();
System.out.println("the master key is " + masterKey); //successfuly outputs the first line if exists 

编辑 2:资源路径应该以/

InputStream is = getClass().getResourceAsStream("/static/master-key.txt");

标签: javafilepathresourcesembedded-resource

解决方案


InputStream is = getClass().getResourceAsStream("static/master-key.txt");

这是搜索相对于调用它的类的包/目录的资源。很可能实际上可以相对于应用程序结构的根找到资源。为此,请添加一个前导/,就像这样。

InputStream is = getClass().getResourceAsStream("/static/master-key.txt");

推荐阅读