[英]Load Properties file in java
我無法使用以下片段加載屬性文件
URL configURL = null;
URLConnection configURLConn = null;
InputStream configInputStream = null;
currConfigProperties = new Properties();
try {
String configPropertiesFile = getParameter("propertiesFile");
if (configPropertiesFile == null) {
configPropertiesFile = "com/abc/applet/Configuration.properties";
}
System.out.println("configPropertiesFile :"+configPropertiesFile);
configURL = new URL(getCodeBase(), configPropertiesFile);
configURLConn = configURL.openConnection();
configInputStream = configURLConn.getInputStream();
currConfigProperties.load(configInputStream);
} catch (MalformedURLException e) {
System.out.println(
"Creating configURL: " + e);
} catch (IOException e) {
System.out.println(
"IOException opening configURLConn: "
+ e);
}
獲取java.io.FileNotFoundException異常。
您可以通過以下方式將屬性文件加載到Java類中:
InputStream fileStream = new FileInputStream(configPropertiesFile);
currConfigProperties.load(fileStream);
另外,將屬性文件路徑更改為src/com/abc/applet/Configuration.properties
您也可以使用它從類路徑中加載它:
currConfigProperties.load(this.getClass().getResourceAsStream(configPropertiesFile));
從OP的注釋加載是從類路徑開始的。 因此需要使用ClassLoader,
public void load() {
getClass().getResourceAsStream("my/resource");
}
public static void loadStatic() {
Thread.currentThread().getContextClassLoader().getResourceAsStream("my/resource");
}
第一種方法需要在實例上下文中,第二種將在靜態上下文中工作。
如果您的屬性文件與班級放在同一位置:
Properties properties = new Properties();
try {
properties.load(getClass().getResourceAsStream("properties.properties"));
} catch (IOException e) { /*File Not Found or something like this*/}
我的情況是您的屬性位於類文件的根文件夾中:
Properties properties = new Properties();
try {
properties.load(getClass().getClassLoader().getResourceAsStream("properties.properties"));
} catch (IOException e) { /*File Not Found or something like this*/}
另外,您還可以使用-DmyPropertiesFile=./../../properties.properties
將通行證傳遞到屬性文件,然后將其獲取System.getProperty("myPropertiesFile")
。
您也可以嘗試一下。
public static void loadPropertiesToMemory() {
Properties prop = new Properties();
InputStream input = null;
String filePathPropFile = "configuration.properties";
try {
input = App.class.getClassLoader().getResourceAsStream(filePathPropFile);
prop.load(input);
} catch (IOException ex) {
ex.printStackTrace();
}
}
App
是您實現上述方法的類。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.