先附上代码。
package com.property;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Properties;
public class Test {
public static int getSocketPort(String tomcatpath, String propertyName) {
Properties prop = new Properties();
InputStream in = null;
String socketPort = null;
try {
// 加载tomcatpath.properties文件
in = Object.class.getResourceAsStream(tomcatpath);
prop.load(in);
Enumeration it = prop.propertyNames();
while (it.hasMoreElements()) {
String key = (String) it.nextElement();
if (propertyName.equals(key)) {
socketPort = prop.getProperty(key);
break;
}
}
} catch (FileNotFoundException e1) {
throw new RuntimeException(e1);
} catch (IOException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
throw new RuntimeException(e);
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return Integer.parseInt(socketPort);
}
}
package com.property;
public class Main {
public static void main(String[] args) {
int socketPort = Test.getSocketPort("/test/tomcatpath.properties", "tomcat_port");
System.out.println(socketPort);
}
}
在使用Object.class.getResourceAsStream方法时,在src同级目录下创建文件夹configss,文件夹下创建log4j.properties文件和文件夹test,test文件夹下创建文件tomcatpath.properties,如图
此时,执行main函数,程序会直接报错,经过研究,找出问题如下:
需要将configss文件夹执行build path--use as source folder,结果如下图
此时,执行main函数,方法会成功,输出tomcat_port的值。
原因:当将configss文件夹执行build path--use as source folder时,configss文件夹下的配置文件可以被类以相对路径直接读写。(与configss文件夹本身名称无关)