Java中获取运行时资源
在Java中,将运行时资源(如配置文件、图片、模板文件等)放在类路径(classpath)中的某个位置。
使用getResource()方法
URL resourceUrl = getClass().getClassLoader().getResource("config.properties");  
if (resourceUrl != null) {  // 处理URL,例如将其转换为文件路径或读取内容  File file = new File(resourceUrl.toURI()); // 注意:这仅适用于文件系统中的资源  // ...  
} else {  // 资源未找到  
}
使用getResourceAsStream()方法
InputStream inputStream = getClass().getClassLoader().getResourceAsStream("config.properties");  
if (inputStream != null) {  // 读取输入流中的内容,例如使用Properties类加载属性文件  Properties properties = new Properties();  properties.load(inputStream);  // ...  inputStream.close(); // 不要忘记关闭输入流  
} else {  // 资源未找到  
}
说明
URI is not hierarchical
请注意,如果资源在JAR文件中,那么使用toURI()方法将URL转换为File对象可能会失败,因为JAR文件不是文件系统中的一个目录(由于 JAR 文件或其他类路径资源不是文件系统上的实际文件,因此它们没有层次结构的文件路径,因此不能简单地转换为 File 对象)。在这种情况下,你应该直接使用InputStream来读取资源的内容。