相对路径本质上还是绝对路径
- 1.FileTest.class.getResource("")
- 得到的是当前类FileTest.class文件的URI目录。不包括自己!
- 如:file:/D:/java/eclipse32/workspace/jbpmtest3/bin/com/test/
- 2.FileTest.class.getResource("/")
- 得到的是当前的classpath的绝对URI路径。
- 如:file:/D:/java/eclipse32/workspace/jbpmtest3/bin/
- 3.Thread.currentThread().getContextClassLoader().getResource("")
- 得到的也是当前ClassPath的绝对URI路径。
- 如:file:/D:/java/eclipse32/workspace/jbpmtest3/bin/
- 4.FileTest.class.getClassLoader().getResource("")
- 得到的也是当前ClassPath的绝对URI路径。
- 如:file:/D:/java/eclipse32/workspace/jbpmtest3/bin/
- 5.ClassLoader.getSystemResource("")
- 得到的也是当前ClassPath的绝对URI路径。
- 如:file:/D:/java/eclipse32/workspace/jbpmtest3/bin/
- 我推荐使用Thread.currentThread().getContextClassLoader().getResource("")来得到当前的classpath的绝对路径的URI表示法。
Web应用程序,可以作为Web应用程序进行发布和运行。但是,我们也常常会以JavaSE的方式来运行Web应用程序的某个类的main方法。或者,使用JUnit测试。这都需要使用JavaSE的方式来运行。
而目前的JDK提供的ClassLoader类的getResource(String 相对路径)方法,只能接受一般的相对路径。这样,使用ClassLoader类的getResource(String 相对路径)方法就只能定位到classpath下的资源
- import java.io.IOException;
- import java.io.InputStream;
- import java.net.MalformedURLException;
- import java.net.URL;
- import java.util.Properties;
- import org.apache.commons.logging.Log;
- import org.apache.commons.logging.LogFactory;
- /**
- *@author沈东良[email protected]
- *Nov29,2006 10:34:34AM
- *用来加载类,classpath下的资源文件,属性文件等。
- *getExtendResource(StringrelativePath)方法,可以使用../符号来加载classpath外部的资源。
- */
- publicclass ClassLoaderUtil {
- privatestatic Log log=LogFactory.getLog(ClassLoaderUtil.class);
- /**
- *Thread.currentThread().getContextClassLoader().getResource("")
- */
- /**
- *加载Java类。 使用全限定类名
- *@paramclassName
- *@return
- */
- publicstatic Class loadClass(String className) {
- try {
- return getClassLoader().loadClass(className);
- } catch (ClassNotFoundException e) {
- thrownew RuntimeException("class not found '"+className+"'", e);
- }
- }
- /**
- *得到类加载器
- *@return
- */
- publicstatic ClassLoader getClassLoader() {
- return ClassLoaderUtil.class.getClassLoader();
- }
- /**
- *提供相对于classpath的资源路径,返回文件的输入流
- *@paramrelativePath必须传递资源的相对路径。是相对于classpath的路径。如果需要查找classpath外部的资源,需要使用 ../来查找
- *@return 文件输入流
- *@throwsIOException
- *@throwsMalformedURLException
- */
- publicstatic InputStream getStream(String relativePath) throws MalformedURLException, IOException {
- if(!relativePath.contains("../")){
- return getClassLoader().getResourceAsStream(relativePath);
- }else{
- return ClassLoaderUtil.getStreamByExtendResource(relativePath);
- }
- }
- /**
- *
- *@paramurl
- *@return
- *@throwsIOException
- */
- publicstatic InputStream getStream(URL url) throws IOException{
- if(url!=null){
- return url.openStream();
- }else{
- returnnull;
- }
- }
- /**
- *
- *@paramrelativePath必须传递资源的相对路径。是相对于classpath的路径。如果需要查找classpath外部的资源,需要使用 ../来查找
- *@return
- *@throwsMalformedURLException
- *@throwsIOException
- */
- publicstatic InputStream getStreamByExtendResource(String relativePath) throws MalformedURLException, IOException{
- return ClassLoaderUtil.getStream(ClassLoaderUtil.getExtendResource(relativePath));
- }
- /**
- *提供相对于classpath的资源路径,返回属性对象,它是一个散列表
- *@paramresource
- *@return
- */
- publicstatic Properties getProperties(String resource) {
- Properties properties = new Properties();
- try {
- properties.load(getStream(resource));
- } catch (IOException e) {
- thrownew RuntimeException("couldn't load properties file '"+resource+"'", e);
- }
- return properties;
- }
- /**
- *得到本Class所在的ClassLoader的Classpat的绝对路径。
- *URL形式的
- *@return
- */
- publicstatic String getAbsolutePathOfClassLoaderClassPath(){
- ClassLoaderUtil.log.info(ClassLoaderUtil.getClassLoader().getResource("").toString());
- return ClassLoaderUtil.getClassLoader().getResource("").toString();
- }
- /**
- *
- *@paramrelativePath 必须传递资源的相对路径。是相对于classpath的路径。如果需要查找classpath外部的资源,需要使 用../来查找
- *@return资源的绝对URL
- *@throwsMalformedURLException
- */
- publicstatic URL getExtendResource(String relativePath) throws MalformedURLException{
- ClassLoaderUtil.log.info("传入的相对路径:"+relativePath) ;
- //ClassLoaderUtil.log.info(Integer.valueOf(relativePath.indexOf("../"))) ;
- if(!relativePath.contains("../")){
- return ClassLoaderUtil.getResource(relativePath);
- }
- String classPathAbsolutePath=ClassLoaderUtil.getAbsolutePathOfClassLoaderClassPath();
- if(relativePath.substring(0, 1).equals("/")){
- relativePath=relativePath.substring(1);
- }
- ClassLoaderUtil.log.info(Integer.valueOf(relativePath.lastIndexOf("../"))) ;
- String wildcardString=relativePath.substring(0,relativePath.lastIndexOf("../")+3);
- relativePath=relativePath.substring(relativePath.lastIndexOf("../")+3);
- int containSum=ClassLoaderUtil.containSum(wildcardString, "../");
- classPathAbsolutePath= ClassLoaderUtil.cutLastString(classPathAbsolutePath, "/", containSum);
- String resourceAbsolutePath=classPathAbsolutePath+relativePath;
- ClassLoaderUtil.log.info("绝对路径:"+resourceAbsolutePath) ;
- URL resourceAbsoluteURL=new URL(resourceAbsolutePath);
- return resourceAbsoluteURL;
- }
- /**
- *
- *@paramsource
- *@paramdest
- *@return
- */
- privatestaticint containSum(String source,String dest){
- int containSum=0;
- int destLength=dest.length();
- while(source.contains(dest)){
- containSum=containSum+1;
- source=source.substring(destLength);
- }
- return containSum;
- }
- /**
- *
- *@paramsource
- *@paramdest
- *@paramnum
- *@return
- */
- privatestatic String cutLastString(String source,String dest,int num){
- // String cutSource=null;
- for(int i=0;i<num;i++){
- source=source.substring(0, source.lastIndexOf(dest, source.length()-2)+1);
- }
- return source;
- }
- /**
- *
- *@paramresource
- *@return
- */
- publicstatic URL getResource(String resource){
- ClassLoaderUtil.log.info("传入的相对于classpath的路径:"+resource) ;
- return ClassLoaderUtil.getClassLoader().getResource(resource);
- }
- /**
- *@paramargs
- *@throwsMalformedURLException
- */
- publicstaticvoid main(String[] args) throws MalformedURLException {
- //ClassLoaderUtil.getExtendResource("../spring/dao.xml");
- //ClassLoaderUtil.getExtendResource("../../../src/log4j.properties");
- ClassLoaderUtil.getExtendResource("log4j.properties");
- System.out.println(ClassLoaderUtil.getClassLoader().getResource("log4j.properties").toString());
- }
- }
使用硬编码的绝对路径是完全没有必要的!它一定会让你死的很难看!程序将无法移植!
常用:
字符串类型:System.getProperty("user.dir");
综合:
- package com.zcjl.test.base;
- import java.io.File;
- public class Test {
- public static void main(String[] args) throws Exception {
- System.out.println(
- Thread.currentThread().getContextClassLoader().getResource(""));
- System.out.println(Test.class.getClassLoader().getResource(""));
- System.out.println(ClassLoader.getSystemResource(""));
- System.out.println(Test.class.getResource(""));
- System.out.println(Test.class.getResource("/"));
- System.out.println(new File("").getAbsolutePath());
- System.out.println(System.getProperty("user.dir"));
- }
- }
- file:/E:/workSpace/javaTest/target/classes/
- file:/E:/workSpace/javaTest/target/classes/
- file:/E:/workSpace/javaTest/target/classes/
- file:/E:/workSpace/javaTest/target/classes/javaAPI/
- file:/E:/workSpace/javaTest/target/classes/
- E:\workSpace\javaTest
- E:\workSpace\javaTest
(1).Weblogic
WebApplication的系统文件根目录是你的weblogic安装所在根目录。
例如:如果你的weblogic安装在c:\bea\weblogic700.....
那么,你的文件根路径就是c:\.
所以,有两种方式能够让你访问你的服务器端的文件:
a.使用绝对路径:
比如将你的参数文件放在c:\yourconfig\yourconf.properties,
直接使用 new FileInputStream("/yourconfig/yourconf.properties");
b.使用相对路径:
相对路径的根目录就是你的webapplication的根路径,即WEB-INF的上一级目录,将你的参数文件放在yourwebapp\yourconfig\yourconf.properties,
这样使用:
new FileInputStream("yourconfig/yourconf.properties");
这两种方式均可,自己选择。
(2).Tomcat
在类中输出System.getProperty("user.dir");显示的是%Tomcat_Home%/bin
(3).Resin
不是你的JSP放的相对路径,是JSP引擎执行这个JSP编译成SERVLET
的路径为根.比如用新建文件法测试File f = new File("a.htm");
这个a.htm在resin的安装目录下
(4).如何读相对路径哪?
在Java文件中getResource或getResourceAsStream均可
例:getClass().getResourceAsStream(filePath);//filePath可以是"/filename",这里的/代表web发布根路径下WEB-INF/classes
也可以getClass().getClassLoader().getResourceAsStream(filePath)//filePath不是带“/”的
(5).获得文件真实路径
string file_real_path=request.getRealPath("mypath/filename");
通常使用request.getRealPath("/");
4.遗留问题
目前new FileInputStream()只会使用绝对路径,相对
- InputStream in1 = new FileInputStream("abc1.properties"); // 相对路径
- InputStream in2 = new FileInputStream("/abc2.properties"); // 绝对路径,E盘下
- InputStream in3 = new FileInputStream("e://abc3.properties"); //相对路径
配 置文件是应用系统中不可缺少的,可以增加程序的灵活性。java.util.Properties是从jdk1.2就有的类,一直到现在都支持load ()方法,jdk1.4以后save(output,string) ->store(output,string)
getResourceAsStream("xx.properties") 获取;
Application可以通过new FileInputStream("xx.properties");直接在classes一级获取。关键是有时我们需要通过web修改配置文件,我们不 能将路径写死了。经过测试觉得有以下心得:
1.servlet中读写。如果运用Struts 或者Servlet可以直接在初始化参数中配置,调用时根据servlet的getRealPath("/")获取真实路径,再根据String file = this.servlet.getInitParameter("abc");
例:
- InputStream input = Thread.currentThread().getContextClassLoader().
- getResourceAsStream("abc.properties");
- Properties prop = new Properties();
- prop.load(input);
- input.close();
- OutputStream out = new FileOutputStream(path);
- prop.setProperty("abc", “test");
- prop.store(out, “–test–");
- out.close();
例:
- // jsp页面
- String path = pageContext.getServletContext().getRealPath("/");
- String realPath = path+"/WEB-INF/classes/abc.properties";
- //java 程序
- InputStream in = getClass().getClassLoader().getResourceAsStream("abc.properties"); // abc.properties放在webroot/WEB-INF/classes/目录下
- prop.load(in);
- in.close();
- OutputStream out = new FileOutputStream(path); // path为通过页面传入的路径
- prop.setProperty("abc", “abcccccc");
- prop.store(out, “–test–");
- out.close();
- 3.只通过Java程序操作资源文件
- InputStream in = new FileInputStream("abc.properties"); // 相对路径,项目下的路径
-
OutputStream out = new FileOutputStream("abc.properties");