在Java中,可以使用以下代码读取JAR包中的配置文件:
import java.io.InputStream; import java.util.Properties; public class ReadConfigFile { public static void main(String[] args) { try { // 读取JAR包中的配置文件 InputStream inputStream = ReadConfigFile.class.getResourceAsStream("/config.properties"); // 创建Properties对象 Properties properties = new Properties(); // 加载配置文件 properties.load(inputStream); // 获取配置项的值 String value = https://www.yisu.com/ask/properties.getProperty("key"); System.out.println("Value: " + value); // 关闭输入流 inputStream.close(); } catch (Exception e) { e.printStackTrace(); } } }
上述代码中,ReadConfigFile
类通过getResourceAsStream
方法获取JAR包中的配置文件config.properties
的输入流。然后使用Properties
对象加载配置文件,并通过getProperty
方法获取配置项的值。
请注意,要使用绝对路径来指定JAR包中的配置文件,即以/
开头。