如何在Jenkins插件中加载资源文件?加载时遇FileNotFoundException
Ah, I’ve dealt with this exact headache when building Jenkins plugins! The root cause here is straightforward: once your plugin is packaged into a JAR (which Jenkins deploys as part of the plugin bundle), your properties.txt isn’t a standalone file on the server’s filesystem anymore—it’s embedded inside the JAR archive. Using standard File class methods to access it will throw that error because the OS can’t locate a "real" file at that jar-internal path.
Here’s how to fix it, step by step:
Use ClassLoader to get a resource stream instead of a file path
This is the standard way to access embedded resources in Java/JVM applications. You have two reliable approaches:Using your current class’s classloader (most straightforward for plugin code):
// The leading slash ensures we look from the root of the JAR InputStream resourceStream = getClass().getResourceAsStream("/properties.txt");If your
properties.txtis nested in a subdirectory undersrc/main/resources(e.g.,src/main/resources/config/), adjust the path to/config/properties.txt.Using the thread context classloader (useful if you’re in a utility class without access to a specific class instance):
InputStream resourceStream = Thread.currentThread().getContextClassLoader() .getResourceAsStream("properties.txt");Note: No leading slash here—this looks from the JAR’s root by default.
Properly read and close the stream
Always use try-with-resources to ensure the stream is closed automatically, avoiding resource leaks:try (InputStream stream = getClass().getResourceAsStream("/properties.txt"); BufferedReader reader = new BufferedReader(new InputStreamReader(stream))) { String line; while ((line = reader.readLine()) != null) { // Process your properties content here System.out.println(line); } } catch (IOException e) { // Log the error (use Jenkins' logger instead of printStackTrace in production!) e.printStackTrace(); }Double-check common pitfalls
- Case sensitivity: Linux-based Jenkins servers are case-sensitive—make sure your code uses
properties.txt(lowercase) if that’s exactly what’s in yoursrc/main/resourcesdirectory. - Build tool configuration: Ensure Maven/Gradle isn’t excluding your resource. Maven automatically packages all files in
src/main/resourcesby default, but if you’ve customized yourpom.xml’s<resources>section, verify it’s not filtering or excluding the file. For Gradle, check yoursourceSets.resourcesconfiguration. - Classloader context: If you’re still having issues, stick with
getClass().getResourceAsStream()—Jenkins uses a complex classloader hierarchy, and this method ensures you’re using the same classloader that loaded your plugin’s classes, which will have access to your embedded resources.
- Case sensitivity: Linux-based Jenkins servers are case-sensitive—make sure your code uses
内容的提问来源于stack exchange,提问作者pavan

