In the maven project, let's assume that we have a file called "config.cnf" and its location is lower.
/src /main /resources /conf config.cnf
In the IDE (Eclipse), I access this file using the ClassLoader.getResource (..) method, but if I run this application using jar, I always encounter the exception βFile not foundβ. Finally, I wrote a file access method by looking at where the application works.
public static File getResourceFile(String relativePath) { File file = null; URL location = <Class>.class.getProtectionDomain().getCodeSource().getLocation(); String codeLoaction = location.toString(); try{ if (codeLocation.endsWith(".jar"){ //Call from jar Path path = Paths.get(location.toURI()).resolve("../classes/" + relativePath).normalize(); file = path.toFile(); }else{ //Call from IDE file = new File(<Class>.class.getClassLoader().getResource(relativePath).getPath()); } }catch(URISyntaxException ex){ ex.printStackTrace(); } return file; }
If you call this method by sending the "conf / config.conf" parameter, you get access to this file from both the jar and the IDE.
source share