共計 951 個字符,預計需要花費 3 分鐘才能閱讀完成。
可以使用 Java 中的 ClassLoader 來讀取 jar 包下的配置文件。
使用 ClassLoader 的 getResourceAsStream 方法來讀取 jar 包下的配置文件,代碼示例如下:
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class ReadConfigFromJar {public static void main(String[] args) {
// 使用 ClassLoader 加載配置文件
InputStream inputStream = ReadConfigFromJar.class.getClassLoader().getResourceAsStream("config.properties");
Properties properties = new Properties();
try {
// 加載配置文件
properties.load(inputStream);
// 獲取配置項的值
String value = properties.getProperty("key");
System.out.println(value);
} catch (IOException e) {e.printStackTrace();
} finally {if (inputStream != null) {
try {inputStream.close();
} catch (IOException e) {e.printStackTrace();
}
}
}
}
}
在上述示例代碼中,通過 ClassLoader.getResourceAsStream("config.properties")
方法來獲取配置文件的輸入流,然后使用 Properties 類加載輸入流并獲取配置項的值。需要注意的是,配置文件必須位于 classpath 下。
另外,需要將配置文件的路徑以正確的相對路徑方式傳遞給 getResourceAsStream
方法。如果配置文件位于 jar 包的根目錄下,則直接使用文件名即可,如果配置文件位于 jar 包的子目錄下,則需要將目錄路徑和文件名一起傳遞,例如"config/sub_config.properties"
。
丸趣 TV 網 – 提供最優質的資源集合!
正文完
發表至: Java
2023-12-20