当我使用此命令 java -jar myapp.jar
执行 jar 时,我遇到了 FileNotFoundException
。
我的项目是一个基本的 Gradle java 应用程序。我将文件放在 ROOT/src/main/resources/testfile/test1.txt
中。我尝试在 IDE 中运行代码以使用类路径检查文件是否存在。
File file = ResourceUtils.getFile("classpath:testfile/test1.txt");
System.out.println(file.exists());
这是真的,但是当我执行作为命令“gradle build”的结果的构建文件时,我遇到了 FileNotFoundException。当我取消归档 jar 时,我可以看到文件(\BOOT-INF\classes\testfile\test1.txt)
。
其实我想用示例文件部署spring boot jar,我会放初始化的代码。请帮忙。谢谢。
最佳答案
假设您实际上想要读取文件而不是尝试使用类加载器来寻址资源:
InputStream in = getClass().getResourceAsStream("/testfile/test1.txt");
BufferedReader reader = new BufferedReader( new InputStreamReader( in ) );
String line = null;
while( (line = reader.readLine() ) != null )
System.out.println("Line: " + line);
对我有用
关于java - 我想部署在类路径中包含一些文件的 jar,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58339454/