Use getClass().getResourceAsStream("/config.properties") and read the stream. A file in the classpath is not a File on disk once the app is packaged as a JAR.
try (InputStream in = Main.class.getResourceAsStream("/config.properties")) {
if (in == null) throw new FileNotFoundException("config.properties not on the classpath");
String text = new String(in.readAllBytes(), StandardCharsets.UTF_8); // Java 9+
Properties props = new Properties();
// props.load(in) could be used instead of reading the text
}
// Class loader version: no leading slash, always relative to the classpath root
InputStream in2 = Thread.currentThread().getContextClassLoader()
.getResourceAsStream("config.properties");- With Maven or Gradle, put the file under
src/main/resources. Class.getResourceAsStreamtreats a path without a leading slash as relative to the class's package; a leading slash starts at the classpath root.- Avoid
new File(url.getPath()), which works in the IDE and fails inside a JAR.
