java使用相对路径读取xml文件

java使用相对路径读取xml文件:
一、xml文件一般的存放位置有三个:
1.放在WEB-INF下;
2.xml文件放在/WEB-INF/classes目录下或classpath的jar包中;
3.放在与解析它的java类同一个包中,不一定是classpath;

二、相对应的两种使用相对路径的读取方法:

方法一:(未验证)
将xml文件放在WEB-INF目录下,然后
程序代码:
InputStream is=getServletContext().getResourceAsStream( "/WEB-INF/xmlfile.xml" );

方法二:将xml文件放在/WEB-INF/classes目录下或classpath的jar包中,则可以使用ClassLoader的静态方法getSystemResourceAsStream(String s)读取;
程序代码:
String s_xmlpath="com\xml\hotspot.xml";
InputStream in=ClassLoader.getSystemResourceAsStream(s_xmlpath);

方法三:xml在随意某个包路径下:
String s_xmlpath="com\xml\hotspot.xml";
ClassLoader classLoader=HotspotXmlParser.class.getClassLoader();
InputStream in=classLoader.getResourceAsStream(s_xmlpath);


另外

System.out.println(Thread.currentThread().getContextClassLoader().getResource(""));

file:/F:/Tomcat%205.0/webapps/DOMTest/WEB-INF/classes/

System.out.println(DomFunction.class.getClassLoader().getResource("").toString());

file:/F:/Tomcat%205.0/webapps/DOMTest/WEB-INF/classes/

System.out.println(ClassLoader.getSystemResource(""));

null

System.out.println(DomFunction.class.getResource("/"));

file:/F:/Tomcat%205.0/webapps/DOMTest/WEB-INF/classes/

System.out.println(DomFunction.class.getResource("/")); //Class文件所在路径

file:/F:/Tomcat%205.0/webapps/DOMTest/WEB-INF/classes/

System.out.println(new File("/").getAbsolutePath());

F:\ System.out.println(System.getProperty("user.dir"));

F:\Tomcat 5.0\bin
路径当中出现的是百分号是由于文件夹或文件名中的空格造成的。
如 :tomcat 5.0则变成了Tomcat%205.0,其中%20即是空格.
String path = getClass().getProtectionDomain().getCodeSource().getLocation().getPath(); 必须是在非静态方法中才可以使用

猜你喜欢

转载自zpball.iteye.com/blog/1277125