Issue
I am accessing a File inside the resources folder from the main class
File file = new ClassPathResource("remoteUnitsIdsInOldServer.txt").getFile();
and I am getting this error:
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
and I even open the jar file and the file remoteUnitsIdsInOldServer.txt is there, inside classes
Solution
It's depends on your requirements..
Case 1:
Considering you need to access text file from resource. You can simply use apache IOUtils
and java ClassLoader
.
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();
}
Classic way:
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();
}
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.
Answered By - Mohanraj
Answer Checked By - Timothy Miller (JavaFixing Admin)