共計 1033 個字符,預計需要花費 3 分鐘才能閱讀完成。
要讀取 config 目錄下的配置文件,可以使用 Java 中的 Properties 類來實現。
首先,需要通過類加載器獲取到配置文件的輸入流。假設配置文件的名字是 config.properties,可以使用以下代碼獲取到輸入流:
InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("config/config.properties");
接下來,可以使用 Properties 類加載輸入流,并讀取配置文件中的內容:
Properties properties = new Properties();
properties.load(inputStream);
現在,配置文件中的內容已經加載到 Properties 對象中了。可以通過 getProperty() 方法來獲取配置項的值:
String configValue = properties.getProperty("config.key");
其中,config.key 是配置項的鍵值。
完整的代碼示例:
import java.io.InputStream;
import java.util.Properties;
public class ConfigReader {public static void main(String[] args) {
try {
// 獲取配置文件的輸入流
InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("config/config.properties");
// 加載配置文件
Properties properties = new Properties();
properties.load(inputStream);
// 讀取配置項的值
String configValue = properties.getProperty("config.key");
System.out.println("配置項的值是:" + configValue);
// 關閉輸入流
inputStream.close();} catch (Exception e) {e.printStackTrace();
}
}
}
請確保配置文件 config.properties 位于 config 目錄下,并且在類路徑中可訪問到。
丸趣 TV 網 – 提供最優質的資源集合!
正文完
發表至: Java
2023-12-20