拷贝下面这个类,然后测试一下里面的path
/**
* 在如下环境下进行了测试
*
* Test Environment
* Windows Linux Unix
* Tomcat6.0.10
* Resin3.1.1
* Jboss4.0.0/5.0.0
* WebLogic9.1
* WebSphere6.1
* WasCE1.1
* Apusic4.0.3
* JFox3
* Jetty6.1.3
*
*
*/
public abstract class Path{
public static final String CLASS_PATH;
public static final String WEB_INF_PATH;
public static final String APP_PATH;
public static final String ROOT_PATH;
public static final String UserRegister;//玩家注册
public static final String sqlFilePath;//sql临时保存文件
static{
String currentPath=getPath(Path.class);
if(currentPath.indexOf(".jar!/")>-1||currentPath.indexOf("classes")>-1){
String classPath=currentPath.replaceAll("/./","/"); //weblogic
classPath=classPath.replaceAll("/lib/([^\'']+)!/","/classes/"); //jar
classPath=classPath.split("/classes/")[0]+"/classes/";
//if os is not windows system
if(classPath.indexOf(':')<0){
classPath='/'+classPath;
}
CLASS_PATH=classPath;
}else{
CLASS_PATH=Path.class.getClassLoader().getResource(".").getPath().substring(1);
}
WEB_INF_PATH=CLASS_PATH.substring(0,CLASS_PATH.substring(0,CLASS_PATH.lastIndexOf('/')).lastIndexOf('/')+1);
APP_PATH=WEB_INF_PATH.substring(0,WEB_INF_PATH.substring(0,WEB_INF_PATH.lastIndexOf('/')).lastIndexOf('/')+1);
ROOT_PATH=CLASS_PATH.substring(0,CLASS_PATH.indexOf('/')+1);
UserRegister=WEB_INF_PATH+"register.properties";
sqlFilePath =WEB_INF_PATH+"sqlFile.txt";
//UserRegister=WEB_INF_PATH.substring(0,WEB_INF_PATH.indexOf("WebRoot"))+"src/com/farmerwar/user/register.properties";
}
/**
* 获取参数cls的目录路径
* @param cls
* @return
*/
public static String getPath(Class> cls){
String t=getAbsoluteFile(cls);
return t.substring(0,t.lastIndexOf('/')+1).replaceAll("(file:/)|(file:)|(wsjar:)|(jar:)|(zip:)","");
// t=t.replaceAll("file:/", ""); //windows
// t=t.replaceAll("file:", ""); //linux,unix
// t=t.replaceAll("wsjar:",""); //websphere wsjar: has to at jar: before
// t=t.replaceAll("jar:",""); //tomcat,jboss,resin,wasce,apusic
// t=t.replaceAll("zip:",""); //weblogic
}
/**
* 获取参数cls的文件路径
* @param cls
* @return
*/
public static String getAbsoluteFile(Class> cls){
return cls.getResource(cls.getSimpleName() + ".class").toString().replaceAll("%20", " ");
}
public static void main(String args[]){
System.out.println(Path.WEB_INF_PATH);
}
}