![ContractedBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![ExpandedBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
public class RealPath {
public String getRealPath() {
String realPath = this.getClass().getResource("/").toString().substring(6);
realPath = realPath.replace("%20", " ");
//下面是根据windows,linux不同做转义,具体看情况
//realPath = realPath.replace("/", "\\\\");
return realPath;
}
}
如果是在static方法中可以这样取:
String realPath
=
Config.
class
.getResource(
"
/
"
).toString().substring(
6
); //这里的Config是当前的类名
realPath = realPath.replace( " %20 " , " " );
//realPath = realPath.replace( " / " , " \\ " );
realPath = realPath.replace( " %20 " , " " );
//realPath = realPath.replace( " / " , " \\ " );
class.getResource("/") --> 返回class文件所在的顶级目录,一般为包名的顶级目录。
--> file:\D:\work\test\WebRoot\WEB-INF\classes\pubkey.key
其中.substring(6)是将file:\截去
这里顺便提供一位朋友的文章,对getResource()方法的用法写的挺详细的。
http://gavin-chen.javaeye.com/blog/261151