问题
- 在java中读取properties属性,发现配置的读取路径找不到properties文件。
InputStream in;
Properties pro = new Properties();
in = new FileInputStream(new File("src/config/data.properties"));
pro.load(in);
- 此处路径写的不对,试过另一种方式,可以读取到文件并解析属性,但是如果这段代码是在web工程的某个jar包内,则这种方式在tomcat下没问题,但放在websphere上就获取不到路径了。
Test.class.getResource("/").getPath() + "/config/data.properties"
解决
/**
* 取得当前类所在的文件
* @param clazz
* @return
*/
public static File getClassFile(Class clazz){
URL path = clazz.getResource(clazz.getName().substring(
clazz.getName().lastIndexOf(".")+1)+".classs");
if(path == null){
String name = clazz.getName().replaceAll("[.]", "/");
path = clazz.getResource("/"+name+".class");
}
return new File(path.getFile());
}
/**
* 得到当前类的路径
* @param clazz
* @return
*/
public static String getClassFilePath(Class clazz){
try{
return java.net.URLDecoder.decode(getClassFile(clazz).getAbsolutePath(),"UTF-8");
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
return "";
}
}
/**
* 取得当前类所在的ClassPath目录,比如tomcat下的classes路径
* @param clazz
* @return
*/
public static File getClassPathFile(Class clazz){
File file = getClassFile(clazz);
for(int i=0,count = clazz.getName().split("[.]").length; i<count; i++)
file = file.getParentFile();
if(file.getName().toUpperCase().endsWith(".JAR!")){
file = file.getParentFile();
}
return file;
}
/**
* 取得当前类所在的ClassPath路径
* @param clazz
* @return
*/
public static String getClassPath(Class clazz){
try{
return java.net.URLDecoder.decode(getClassPathFile(clazz).getAbsolutePath(),"UTF-8");
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
return "";
}
}
通过上面的方法调用就可以了
InputStream in;
Properties pro = new Properties();
String clspath = getClassPath(LoadMiddleTables.class);
in = new FileInputStream(new File(clspath+"/config/data.properties"));
pro.load(in);