SpringBoot-访问资源文件夹中的文件 [英] SpringBoot - accessing a file inside resources folder
问题描述
我正在从主类访问资源文件夹中的文件
I am accessing a File inside the resources folder from the main class
File file = new ClassPathResource("remoteUnitsIdsInOldServer.txt").getFile();
我收到此错误:
java.io.FileNotFoundException: class path resource [remoteUnitsIdsInOldServer.txt] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/Users/lopes/Documents/workspace-sts-3.9.0.RELEASE/telefonicaUtils/target/telefonicaUtils-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/remoteUnitsIdsInOldServer.txt
我什至打开了jar文件,并且在类内部有文件remoteUnitsIdsInOldServer.txt
and I even open the jar file and the file remoteUnitsIdsInOldServer.txt is there, inside classes
推荐答案
这取决于您的要求.
考虑到您需要从资源访问文本文件.您可以简单地使用apache IOUtils
和java ClassLoader
.
Considering you need to access text file from resource. You can simply use apache IOUtils
and java ClassLoader
.
代码段(请注意:IOUtils程序包-> org.apache.commons.io.IOUtils)
Snippet (note: IOUtils package --> org.apache.commons.io.IOUtils)
String result = "";
ClassLoader classLoader = getClass().getClassLoader();
try {
result = IOUtils.toString(classLoader.getResourceAsStream("fileName"));
} catch (IOException e) {
e.printStackTrace();
}
经典方式:
StringBuilder result = new StringBuilder("");
//Get file from resources folder
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("fileName").getFile());
try (Scanner scanner = new Scanner(file)) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
result.append(line).append("\n");
}
scanner.close();
} catch (IOException e) {
e.printStackTrace();
}
情况2:
考虑到您需要从诸如xml,属性文件之类的资源中访问属性.
它太简单了,只需使用spring注释@ImportResource({ "classpath:application-properties.xml", "classpath:context.properties" })
希望对您有所帮助.
Case 2:
Considering you need to access properties from resources such as xml, properties files.
Its too simple, Simply use spring annotation @ImportResource({ "classpath:application-properties.xml", "classpath:context.properties" })
Hope that will be helpful to you.
这篇关于SpringBoot-访问资源文件夹中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!