java - 无法从资源文件夹中读取文件
问题描述
最终编辑:现在代码看起来像这样
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");
解决方案
InputStream is = getClass().getResourceAsStream("static/master-key.txt");
这是搜索相对于调用它的类的包/目录的资源。很可能实际上可以相对于应用程序结构的根找到资源。为此,请添加一个前导/
,就像这样。
InputStream is = getClass().getResourceAsStream("/static/master-key.txt");
推荐阅读
- c++ - 如何同时发送多个包裹?
- javascript - 如何在Angular中的其他方法之前执行订阅块?
- nrf52 - Zephyr 应用程序构建失败
- javascript - 如何控制html页面打印中的溢出内容?
- google-apis-explorer - Display & Video 360 - 如何在没有报告的情况下检索效果数据?
- exif - 保存后缺少Exif数据Filepond Vue
- amazon-dynamodb - 字符串的 Dynamodb BETWEEN 操作
- android - 应用程序销毁时将图像保存到存储中。Uri 无法在位图中转换
- javascript - 尝试在 Javascript 中将元素添加到组会导致“......不是对象”。即使元素是对象也会出错
- javascript - 如何在Javascript中将对象的字段名称转换为值