en *_*pes 5 java file-io spring spring-boot
我正在从主类访问资源文件夹内的文件
File file = new ClassPathResource("remoteUnitsIdsInOldServer.txt").getFile();
Run Code Online (Sandbox Code Playgroud)
我收到此错误:
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
Run Code Online (Sandbox Code Playgroud)
我什至打开 jar 文件,文件 remoteUnitsIdsInOldServer.txt 就在那里,在类内部
这取决于你的要求..
考虑到您需要从资源访问文本文件。您可以简单地使用apache IOUtilsjava ClassLoader。
片段(注:IOUtils 包 --> org.apache.commons.io.IOUtils)
String result = "";
ClassLoader classLoader = getClass().getClassLoader();
try {
result = IOUtils.toString(classLoader.getResourceAsStream("fileName"));
} catch (IOException e) {
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
经典方式:
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();
}
Run Code Online (Sandbox Code Playgroud)
考虑到您需要从 xml、属性文件等资源访问属性。太简单了,直接使用spring注解@ImportResource({ "classpath:application-properties.xml", "classpath:context.properties" })
希望对你有帮助。
| 归档时间: |
|
| 查看次数: |
19450 次 |
| 最近记录: |