如何获取Java项目的绝对路径
如何获取Java项目的绝对路径
------解决方案--------------------给楼主一个我写的例子,希望有所帮助:
import java.io.File;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Document;
import
org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class XmlRead {
private static String xmlurl;
/**
* 初始化
*
*/
public XmlRead() {
String path = getClass().getProtectionDomain().getCodeSource()
.getLocation().getPath();
if (path.indexOf( "WEB-INF ") > 0) {
path = path.substring(0, path.indexOf( "/WEB-INF/ ") + 9);
}
this.xmlurl = path;
}
/**
* 根据参数名获得对应参数的值
* @param name
* @return
*/
public static String getXmlValueByName(String name) {
XmlRead xmlread=new XmlRead();
String value = null;
if (name != null) {
SAXReader reader = new SAXReader();
try {
Document document = reader.read(new File(xmlread.xmlurl
+ "/ttms-config.xml "));
List list = document.selectNodes( "/root/Element ");// 读取配置文件
Iterator iter = list.iterator();
while (iter.hasNext()) {
Element element = (Element) iter.next();
String elementName = element.elementText( "Name ");
if (elementName.equals(name)) {
value = element.elementText( "Value ");
break;
}
}
} catch (DocumentException e) {
e.printStackTrace();
return null;
}
}
return value;
}
}