|
如何才能得到得到类的绝对路径呢?最近发现原来写的得到类的绝对路径的方法,在有些时候会出错,可能会得到类似:C:\Documents%20and%20Settings\cuilichen\Local%20Settings\Temp的路径。显然,这不是我们需要的路径。因此,需要找到另外的方法原始方法是:
/** * 得到文件的绝对路径 * * @return String */ public String getPath() { String strClassName = getClass().getName(); String strClassFileName = strClassName.substring(strClassName .lastIndexOf(".") + 1, strClassName.length()); URL url = getClass().getResource(strClassFileName + ".class"); String strURL = url.toString(); strURL = strURL.substring(strURL.indexOf("/") + 1); return strURL; }
这里采用的新方式是:
/** * 得到文件的绝对路径 * * @return String */ public String getPath2() throws Exception { String strClassName = getClass().getName(); String strClassFileName = strClassName.substring(strClassName .lastIndexOf(".") + 1, strClassName.length()); File file = new File(strClassFileName + ".class"); return file.getCanonicalPath(); }
|