Ubuntu下Eclipse读取config.properties文件路径错误的解决方法
解决Java读取配置文件时URL为空的NullPointerException问题
问题背景
在Ubuntu 20.0系统的Eclipse环境中,使用以下Java代码读取config.properties时抛出NullPointerException,提示myURL为null无法调用openStream():
public static String getProperty(String key) { Properties properties = new Properties(); try { URL myURL = LoginProperty.class.getClassLoader().getResource("/global/resources/config.properties"); InputStream input = myURL.openStream(); properties.load(input); } catch (IOException e) { SendErrorsToAdmin.setMsg(LoginProperty.class.getClass().getCanonicalName(), e); } return properties.getProperty(key); }
项目结构中,config.properties位于src/main/resources/global/resources/目录下。
解决方案
1. 修正资源路径
类加载器的getResource()方法路径是相对于类路径根目录(即src/main/resources,编译后对应target/classes目录)。原路径开头的/虽表示类路径根,但实际文件结构下,正确路径应为global/resources/config.properties(加不加/效果一致,需与实际路径匹配)。同时建议增加空判断避免NPE:
public static String getProperty(String key) { Properties properties = new Properties(); try { // 修正路径,可选择去掉开头的/ URL myURL = LoginProperty.class.getClassLoader().getResource("global/resources/config.properties"); if (myURL == null) { throw new IOException("配置文件global/resources/config.properties未找到"); } InputStream input = myURL.openStream(); properties.load(input); input.close(); // 关闭输入流,避免资源泄漏 } catch (IOException e) { SendErrorsToAdmin.setMsg(LoginProperty.class.getCanonicalName(), e); } return properties.getProperty(key); }
2. 确保资源文件夹被正确标记
在Eclipse中,右键src/main/resources文件夹 → Build Path → Use as Source Folder。这样Eclipse编译时会自动将该文件夹下的所有文件复制到类路径目录,保证类加载器能找到配置文件。
3. 更简洁的读取方式(推荐)
使用Class.getResourceAsStream()直接获取输入流,无需处理URL,路径规则与ClassLoader.getResource()一致(开头加/表示类路径根):
public static String getProperty(String key) { Properties properties = new Properties(); try (InputStream input = LoginProperty.class.getResourceAsStream("/global/resources/config.properties")) { if (input == null) { throw new IOException("配置文件global/resources/config.properties未找到"); } properties.load(input); } catch (IOException e) { SendErrorsToAdmin.setMsg(LoginProperty.class.getCanonicalName(), e); } return properties.getProperty(key); }
这里使用try-with-resources语法,会自动关闭输入流,避免资源泄漏。
错误原因
原代码中myURL为null的核心原因:
- 资源路径与实际文件位置不匹配;
src/main/resources未被标记为Source Folder,导致编译时配置文件未被复制到类路径下。
内容的提问来源于stack exchange,提问作者MikeJ
相关产品推荐
相关产品推荐

