加载属性文件在java中
问题描述:
我不能用下面来加载属性文件片断加载属性文件在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
你也可以用它来从classpath加载你的属性文件的路径: -
currConfigProperties.load(this.getClass().getResourceAsStream(configPropertiesFile));
答
从OP的评论加载是从类路径。因此,需要使用ClassLoader,第一种方法需要在实例上下文中,第二种方法需要在静态上下文中工作。
答
在情况下,当你的属性在同一个地方文件,你的类:
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")
。
我想这将工作=> configPropertiesFile =“src/com/abc/applet/Configuration.properties” – Juvanis 2013-03-19 11:24:33
大概这是一个从远程服务器加载的小程序?还是你想从类路径中读取?无论哪种方式,请尝试'ClassLoader.getResourceAsStream'方法。 – 2013-03-19 11:25:49
@ bmorris591 - classpath – happy 2013-03-19 11:26:26