Java 路径

Java路径中的空格问题
1, TestURL().class.getResource("").getPath()或TestURL().class.getResource("").getFile()获得的路径,不能被FileReader()和FileWriter()直接应用。
  原因是URL对空格,特殊字符(%,#,[]等)和中文进行了编码处理。
  例如:空格变为%20。
  有解决方法(1),使用repaceAll("%20",' ')替换后,只能解决空格问题。但是路径中包含%和中文就不行了。
  有解决方法(2),使用URLDecoder.decode(str,"UTF-8")解码,但是只能解决一部分,若路径中含有+,也是不能解决的,原因是URL并不是完全用URLEncoder.encode(str,"UTF-8")编码的,+号被解码后,却变成了空格。
方法(3),可以解决所有的问题,用TestURL().class.getResource("").toURI().getPath(),但是需要处理URISyntaxException异常,比较麻烦点。

java 路径中的空格问题
若路径中带空格,则
1. uri.getpath();返回的路径中的空格仍以“空格”的形式出现,如/F:/MyEclipse Workspace/project/bin/...
除此之外,URL返回的一切路径中的空格都以“%20”的形式出现,uri.toString()也以“%20”的形式出现。

2. new File(String filePath);接受正确URI格式的参数和带“空格”(非20%)的正确相对/绝对字符串路径,否则即使给的路径是正确的也会出现找不到文件的异常。

3. URL/URI返回的路径分隔符都是“/”,File返回的路径分隔符都为“\”。对于存在的文件返回的路径字符串,空格都以"空格"出现,而不存在的路径new出的file,getPath()返回的路径中的空格,仍是new File(String filePath)的参数中原有的形式,即若filePath中是空格的getPath()返回的仍是空格,是“%20”的仍是“%20”。

4.new URL();的参数可以为正确的URI,或者为URI格式的字符串;若字符串是非完整的URI格式,则创建失败。

5.File.toURI()会将file的路径名中的“空格”转化为“%20”,然后在路径前加protocol:"file:/",而 File.toURL()只会在file路径前简单的加上protocol:"file:/",而不会将“空格”转化为“%20”,原来的无论是“空格” 还是“%20”都只会原样保留!

6.Woden 中WSDLReader.readWSDL(String s)的实现要将参数s转化为URL,所以字符串参数s中一定不能有空格,应以“20%”代替。参数s最好为标准的URI格式的字符串。
java 路径解决方案

Java的路径问题,相对来说就比较繁杂。最近的工作涉及到创建和读取文件的工作,现将实际使用中遇到的问题总结如下:
一 相对路径的解释
   1.相对路径(即相对于当前用户目录的相对路径)均可通过以下方式获得(不论是一般的java项目还是web项目)
    String relativelyPath=System.getProperty("user.dir");
   对于一般的java项目中的文件是相对于项目的根目录,而对于web项目中的文件路径,可能是服务器的某个路径,同时不同的web服务器也不同(tomcat是相对于 tomcat安装目录\bin)。为此,个人认为,在web项目中,最好不要使用“相对于当前用户目录的相对路径”。然而默认情况下,java.io 包中的类总是根据当前用户目录来分析相对路径名。此目录由系统属性 user.dir 指定,通常是 Java 虚拟机的调用目录。这就是说,在使用java.io包中的类时,最好不要使用相对路径。否则,虽然在SE程序中可能还算正常,但是到了EE程序中,弄不好,就会带来问题一片哦。
   2.相对于classpath的相对路径
   如:相对于file:/D:/mywork/javaprj/MyTest/bin这个路径的相对路径。其中,bin是本项目的classpath。所有的Java源文件编译后的.class文件复制到这个目录中。
二 类加载目录(即当运行某一类时获得其装载目录)
   1.不论是一般的java项目还是web项目,先定位到能看到包路径的第一级目录   
        InputStream is=ReadWrite.class.getClassLoader().getResourceAsStream("DeviceNO");
    其中,DeviceNO文件的路径为 项目名\src\DeviceNO;类ReadWrite所在包的第一级目录位于src目录下。
    2.与1相似,不同的是此方法必须以'/'开头      
    InputStream is=ReadWrite.class.getResourceAsStream("DeviceNO");
    其中,DeviceNO文件的路径为 项目名\src\DeviceNO;类ReadWrite所在包的第一级目录位于src目录下。
三. web项目根目录获取
    1. 可建立一个servlet,在其init方法中写入如下语句
      ServletContext sc=this.getServletContext();
     String temp=sc.getRealPath("/");
     得到的输出路径结果类似:"D:\Apache\Tomcat6.0\webapps\windpower\ " (windpower为项目名字) ,如果是调用了s1.getRealPath("")则输出"D:\Apache\Tomcat6.0\webapps\windpower"(注意,在最后少了一个"\")
     2. 在httpServletRequest中,可以通过下面语句
             String cp=request.getSession().getServletContext().getRealPath("/"); 得到的输出路径结果类似:"D:\Apache\Tomcat6.0\webapps\windpower\ "
四 .类路径( classpath)的获取(在Eclipse/MyEclipse中,则为获得src或者classes目录的路径)
    方法1.  Thread.currentThread().getContextClassLoader().getResource("").getPath()
     例如:
     String path=Thread.currentThread().getContextClassLoader().getResource("").getPath();
     System.out.println(path);
     打印:“/D:/windpower/WebRoot/WEB-INF/classes/”
    方法2.   ParsingXML.class.getClassLoader().getResource("").getPath()(ParsingXML为src某一个包中的类,下同)
     例如:
      String path=ParsingXML.class.getClassLoader().getResource("").getPath();
     System.out.println("ParsingXML.class.getClassLoader().getResource--"+path);
     打印: “ParsingXML.class.getClassLoader().getResource--/D:/windpower/WebRoot/WEB-INF/classes/”
    另外,如果想把文件放在某一包中,则可以通过以下方式获得到文件所在目录,即先定位到该包的最后一级目录。
     ParsingXML.class.getResource("").getPath();
     例如:
      String path=ParsingXML.class.getResource("").getPath();
     System.out.println("ParsingXML.class.getResource---"+p2);
     打印: “ParsingXML.class.getResource---/D:/windpower/WebRoot/WEB-INF/classes/parsing/ ”(ParsingXML为src目录下parsing包中的类)
五. 属性文件的读取:
     方法1.
      static {
ps = new Properties();
try {
InputStream in = ReadWrite.class.getResourceAsStream("DeviceNO");
ps.load(in);
in.close();
} catch (Exception e) {
e.printStackTrace();
}
          ps.getProperty("key")
    方法2.
        Locale locale = Locale.getDefault(); 
       ResourceBundle localResource = ResourceBundle.getBundle("windpower/DeviceNOProperties", locale); 
       String value = localResource.getString("1"); 
       System.out.println("DeviceNO: " + value);
       工程src目录下文件DeviceNOProperties.properties(名字后缀必须为properties)文件内容如下:1=3输出结果为:“DeviceNO:3”
六.编码转换问题:
    ClassLoader的getResource方法使用了utf-8对路径信息进行了编码,当路径中存在中文和空格时,他会对这些字符进行转换,这样,得到的往往不是我们想要的真实路径,在此,调用了URLDecoder的decode方法进行解码,以便得到原始的中文及空格路径
例如:结果是file:/C:/Documents%20and%20Settings/%e5%ba%84%e6%99%93%e6%af%85  
  /Local%20Settings/Temp/temp0.jar!/db/dmozdata.mdb  
  而我们期望是 C:/Documents 路径p source  等等。这里我们只要在获取到路径之前把返回值decode下就可以了. 用utf-8编码. Java代码 :
    String configPath = this.getClass().getClassLoader().getResource("allowPath.xml").getFile();
    configPath = java.net.URLDecoder.decode(configPath,"utf-8");
    另外java中URL 的编码和解码函数java.net.URLEncoder.encode(String s)和java.net.URLDecoder.decode(String s);在javascript 中URL 的编码和解码函数escape(String s)和unescape(String s) ;  
七.总结:
     我们在使用相对路径时,应当使用相对于当前classpath的相对路径。
ClassLoader类的getResource(String name),getResourceAsStream(String name)等方法,使用相对于当前项目的classpath的相对路径来查找资源。
读取属性文件常用到的ResourceBundle类的getBundle(String path)也是如此。
通过查看ClassLoader类及其相关类的源代码,发现它实际上还是使用了URI形式的绝对路径。通过得到当前classpath的URI形式的绝对路径,再去构建相对路径的URI形式的绝对路径。

 

 

 

 

 

 

 

 

 

以下是常用的java路径获取方法:

        String userDir = System.getProperty("user.dir");
        System.out.println("user.dir       :" + userDir);
        String userJome = System.getProperty("user.home");
        System.out.println("user.home      :" + userJome);
        String javaClassPath = System.getProperty("java.class.path");
        System.out.println("java.class.path:" + javaClassPath);

        String canonicalPath = new File("").getCanonicalPath();
        System.out.println("canonicalPath  :" + canonicalPath);// 获取标准路径
        String absolutePath = new File("").getAbsolutePath();
        System.out.println("absolutePath   :" + absolutePath);// 获取绝对路径

        String currentClassPath = this.getClass().getResource("").toURI().getPath();
        System.out.println("currentClassPath:" + currentClassPath);// 获取当前类路径
        String LoadClassPath = this.getClass().getClassLoader().getResource("").toURI().getPath();
        System.out.println("LoadClassPath   :" + LoadClassPath);// 获取加载类路径


以下是java web项目路径获取方法(toURI解决了空格问题;由于编写完成代码之后我们要进行单元测试,所以projectPath要有两种获取方式):
        String projectPath;
        try {
            projectPath = this.getClass().getClassLoader().getResource("").toURI().getPath() + "users.xml";
        } catch (NullPointerException e) {
            projectPath = System.getProperty("user.dir") + "\\users.xml";
        }
        System.out.println("projectPath:" + projectPath);// 获取项目路径

以下是他人收集的非常好的网址:

Java路径问题解决方案收集:http://www.cnblogs.com/rongxh7/archive/2010/04/22/1718178.html
Java获取当前路径:http://www.cnblogs.com/diyunpeng/archive/2011/06/06/2073567.html
java(Web)中相对路径,绝对路径问题总结:http://www.blogjava.net/meil/archive/2006/10/10/73908.html

 

 

 

 

 

 

 

 

1, TestURL().class.getResource("").getPath()或TestURL().class.getResource("").getFile()获得的路径,不能被FileReader()和FileWriter()直接应用。

  原因是URL对空格,特殊字符(%,#,[]等)和中文进行了编码处理。

  例如:空格变为%20。

  有解决方法(1),使用repaceAll("%20",' ')替换后,只能解决空格问题。但是路径中包含%和中文就不行了。

  有解决方法(2),使用URLDecoder.decode(str,"UTF-8")解码,但是只能解决一部分,若路径中含有+,也是不能解决的,原因是URL并不是完全用URLEncoder.encode(str,"UTF-8")编码的,+号被解码后,却变成了空格。

  方法(3),可以解决所有的问题,用TestURL().class.getResource("").toURI().getPath(),但是需要处理URISyntaxException异常,比较麻烦点。

 

 

 

 

 

 

 

 

 

 

 

 

 

1, TestURL().class.getResource("").getPath()或TestURL().class.getResource("").getFile()获得的路径,不能被FileReader()和FileWriter()直接应用。 
  原因是URL对空格,特殊字符(%,#,[]等)和中文进行了编码处理。 
  例如:空格变为%20。 
  有解决方法(1),使用repaceAll("%20",' ')替换后,只能解决空格问题。但是路径中包含%和中文就不行了。 
  有解决方法(2),使用URLDecoder.decode(str,"UTF-8")解码,但是只能解决一部分,若路径中含有+,也是不能解决的,原因是URL并不是完全用URLEncoder.encode(str,"UTF-8")编码的,+号被解码后,却变成了空格。 
方法(3),可以解决所有的问题,用TestURL().class.getResource("").toURI().getPath(),但是需要处理URISyntaxException异常,比较麻烦点。

 

java 路径中的空格问题

若路径中带空格,则 
1. uri.getpath();返回的路径中的空格仍以“空格”的形式出现,如/F:/MyEclipse Workspace/project/bin/... 
除此之外,URL返回的一切路径中的空格都以“%20”的形式出现,uri.toString()也以“%20”的形式出现。

2. new File(String filePath);接受正确URI格式的参数和带“空格”(非20%)的正确相对/绝对字符串路径,否则即使给的路径是正确的也会出现找不到文件的异常。

3. URL/URI返回的路径分隔符都是“/”,File返回的路径分隔符都为“\”。对于存在的文件返回的路径字符串,空格都以"空格"出现,而不存在的路径new出的file,getPath()返回的路径中的空格,仍是new File(String filePath)的参数中原有的形式,即若filePath中是空格的getPath()返回的仍是空格,是“%20”的仍是“%20”。

4.new URL();的参数可以为正确的URI,或者为URI格式的字符串;若字符串是非完整的URI格式,则创建失败。

5.File.toURI()会将file的路径名中的“空格”转化为“%20”,然后在路径前加protocol:"file:/",而File.toURL()只会在file路径前简单的加上protocol:"file:/",而不会将“空格”转化为“%20”,原来的无论是“空格”还是“%20”都只会原样保留!

6.Woden 中WSDLReader.readWSDL(String s)的实现要将参数s转化为URL,所以字符串参数s中一定不能有空格,应以“20%”代替。参数s最好为标准的URI格式的字符串。

 

 

java 路径解决方案

Java的路径问题,相对来说就比较繁杂。最近的工作涉及到创建和读取文件的工作,现将实际使用中遇到的问题总结如下: 
一 相对路径的解释 
   1.相对路径(即相对于当前用户目录的相对路径)均可通过以下方式获得(不论是一般的java项目还是web项目) 
    String relativelyPath=System.getProperty("user.dir"); 
   对于一般的java项目中的文件是相对于项目的根目录,而对于web项目中的文件路径,可能是服务器的某个路径,同时不同的web服务器也不同(tomcat是相对于 tomcat安装目录\bin)。为此,个人认为,在web项目中,最好不要使用“相对于当前用户目录的相对路径”。然而默认情况下,java.io 包中的类总是根据当前用户目录来分析相对路径名。此目录由系统属性 user.dir 指定,通常是 Java 虚拟机的调用目录。这就是说,在使用java.io包中的类时,最好不要使用相对路径。否则,虽然在SE程序中可能还算正常,但是到了EE程序中,弄不好,就会带来问题一片哦。 
   2.相对于classpath的相对路径 
   如:相对于file:/D:/mywork/javaprj/MyTest/bin这个路径的相对路径。其中,bin是本项目的classpath。所有的Java源文件编译后的.class文件复制到这个目录中。 
二 类加载目录(即当运行某一类时获得其装载目录) 
   1.不论是一般的java项目还是web项目,先定位到能看到包路径的第一级目录    
        InputStream is=ReadWrite.class.getClassLoader().getResourceAsStream("DeviceNO"); 
    其中,DeviceNO文件的路径为 项目名\src\DeviceNO;类ReadWrite所在包的第一级目录位于src目录下。 
    2.与1相似,不同的是此方法必须以'/'开头       
    InputStream is=ReadWrite.class.getResourceAsStream("DeviceNO"); 
    其中,DeviceNO文件的路径为 项目名\src\DeviceNO;类ReadWrite所在包的第一级目录位于src目录下。 
三. web项目根目录获取 
    1. 可建立一个servlet,在其init方法中写入如下语句 
      ServletContext sc=this.getServletContext(); 
     String temp=sc.getRealPath("/"); 
     得到的输出路径结果类似:"D:\Apache\Tomcat6.0\webapps\windpower\ " (windpower为项目名字) ,如果是调用了s1.getRealPath("")则输出"D:\Apache\Tomcat6.0\webapps\windpower"(注意,在最后少了一个"\") 
     2. 在httpServletRequest中,可以通过下面语句 
             String cp=request.getSession().getServletContext().getRealPath("/"); 得到的输出路径结果类似:"D:\Apache\Tomcat6.0\webapps\windpower\ " 
四 .类路径( classpath)的获取(在Eclipse/MyEclipse中,则为获得src或者classes目录的路径) 
    方法1.  Thread.currentThread().getContextClassLoader().getResource("").getPath() 
     例如: 
     String path=Thread.currentThread().getContextClassLoader().getResource("").getPath(); 
     System.out.println(path); 
     打印:“/D:/windpower/WebRoot/WEB-INF/classes/” 
    方法2.   ParsingXML.class.getClassLoader().getResource("").getPath()(ParsingXML为src某一个包中的类,下同) 
     例如: 
      String path=ParsingXML.class.getClassLoader().getResource("").getPath(); 
     System.out.println("ParsingXML.class.getClassLoader().getResource--"+path); 
     打印: “ParsingXML.class.getClassLoader().getResource--/D:/windpower/WebRoot/WEB-INF/classes/” 
    另外,如果想把文件放在某一包中,则可以通过以下方式获得到文件所在目录,即先定位到该包的最后一级目录。 
     ParsingXML.class.getResource("").getPath(); 
     例如: 
      String path=ParsingXML.class.getResource("").getPath(); 
     System.out.println("ParsingXML.class.getResource---"+p2); 
     打印: “ParsingXML.class.getResource---/D:/windpower/WebRoot/WEB-INF/classes/parsing/ ”(ParsingXML为src目录下parsing包中的类) 
五. 属性文件的读取: 
     方法1. 
      static { 
ps = new Properties(); 
try { 
InputStream in = ReadWrite.class.getResourceAsStream("DeviceNO"); 
ps.load(in); 
in.close(); 
} catch (Exception e) { 
e.printStackTrace(); 

          ps.getProperty("key") 
    方法2. 
        Locale locale = Locale.getDefault();  
       ResourceBundle localResource = ResourceBundle.getBundle("windpower/DeviceNOProperties", locale);  
       String value = localResource.getString("1");  
       System.out.println("DeviceNO: " + value); 
       工程src目录下文件DeviceNOProperties.properties(名字后缀必须为properties)文件内容如下:1=3输出结果为:“DeviceNO:3” 
六.编码转换问题: 
    ClassLoader的getResource方法使用了utf-8对路径信息进行了编码,当路径中存在中文和空格时,他会对这些字符进行转换,这样,得到的往往不是我们想要的真实路径,在此,调用了URLDecoder的decode方法进行解码,以便得到原始的中文及空格路径 
例如:结果是file:/C:/Documents%20and%20Settings/%e5%ba%84%e6%99%93%e6%af%85   
  /Local%20Settings/Temp/temp0.jar!/db/dmozdata.mdb   
  而我们期望是 C:/Documents 路径p source  等等。这里我们只要在获取到路径之前把返回值decode下就可以了. 用utf-8编码. Java代码 : 
    String configPath = this.getClass().getClassLoader().getResource("allowPath.xml").getFile(); 
    configPath = java.net.URLDecoder.decode(configPath,"utf-8"); 
    另外java中URL 的编码和解码函数java.net.URLEncoder.encode(String s)和java.net.URLDecoder.decode(String s);在javascript 中URL 的编码和解码函数escape(String s)和unescape(String s) ;   
七.总结: 
     我们在使用相对路径时,应当使用相对于当前classpath的相对路径。 
ClassLoader类的getResource(String name),getResourceAsStream(String name)等方法,使用相对于当前项目的classpath的相对路径来查找资源。 
读取属性文件常用到的ResourceBundle类的getBundle(String path)也是如此。 
通过查看ClassLoader类及其相关类的源代码,发现它实际上还是使用了URI形式的绝对路径。通过得到当前classpath的URI形式的绝对路径,再去构建相对路径的URI形式的绝对路径。

 

 

 

 

 

 

 

 

 

 

 

1.基本概念的理解

绝对路径:绝对路径就是你的主页上的文件或目录在硬盘上真正的路径,(URL和物理路径)例如:
C:xyz est.txt 代表了test.txt文件的绝对路径。http://www.sun.com/index.htm也代表了一个URL绝对路径。

相对路径:相对与某个基准目录的路径。包含Web的相对路径(HTML中的相对目录),例如:在
Servlet中,"/"代表Web应用的跟目录。和物理路径的相对表示。例如:"./" 代表当前目录,"../"代表上级目录。这种类似的表示,也是属于相对路径。
另外关于URI,URL,URN等内容,请参考RFC相关文档标准。

RFC 2396: Uniform Resource Identifiers (URI): Generic Syntax,
(http://www.ietf.org/rfc/rfc2396.txt)


2.关于JSP/Servlet中的相对路径和绝对路径。

2.1服务器端的地址

服务器端的相对地址指的是相对于你的web应用的地址,这个地址是在服务器端解析的(不同于html和javascript中的相对地址,他们是由客户端浏览器解析的)也就是说这时候在jsp和servlet中的相对地址应该是相对于你的web应用,即相对于http: //192.168.0.1/webapp/的。

其用到的地方有:
forward:servlet中的request.getRequestDispatcher(address);这个address是在服务器端解析的,所以,你要forward到a.jsp应该这么写:request.getRequestDispatcher(“/user/a.jsp”)这个/ 相对于当前的web应用webapp,其绝对地址就是:http://192.168.0.1/webapp/user/a.jsp。 sendRedirect:在jsp中<%response.sendRedirect("/rtccp/user/a.jsp");%>

2.22、客户端的地址

所有的html页面中的相对地址都是相对于服务器根目录(http://192.168.0.1/)的,而不是(跟目录下的该Web应用的目录) http://192.168.0.1/webapp/的。 Html中的form表单的action属性的地址应该是相对于服务器根目录(http://192.168.0.1/)的,所以,如果提交到a.jsp 为:action="/webapp/user/a.jsp"或action="<%=request.getContextPath()% >"/user/a.jsp;
提交到servlet为actiom="/webapp/handleservlet" Javascript也是在客户端解析的,所以其相对路径和form表单一样。


因此,一般情况下,在JSP/HTML页面等引用的CSS,Javascript.Action等属性前面最好都加上
<%=request.getContextPath()%>,以确保所引用的文件都属于Web应用中的目录。另外,应该尽量避免使用类似".","./","../../"等类似的相对该文件位置的相对路径,这样当文件移动时,很容易出问题。


3. JSP/Servlet中获得当前应用的相对路径和绝对路径

3.1 JSP中获得当前应用的相对路径和绝对路径
根目录所对应的绝对路径:request.getRequestURI()
文件的绝对路径  :application.getRealPath(request.getRequestURI());
当前web应用的绝对路径 :application.getRealPath("/");
取得请求文件的上层目录:new File(application.getRealPath(request.getRequestURI())).getParent()

3.2 Servlet中获得当前应用的相对路径和绝对路径
根目录所对应的绝对路径:request.getServletPath();
文件的绝对路径 :request.getSession().getServletContext().getRealPath
(request.getRequestURI())
当前web应用的绝对路径 :servletConfig.getServletContext().getRealPath("/");
(ServletContext对象获得几种方式:
javax.servlet.http.HttpSession.getServletContext()
javax.servlet.jsp.PageContext.getServletContext()
javax.servlet.ServletConfig.getServletContext()
)

4.java 的Class中获得相对路径,绝对路径的方法

4.1单独的Java类中获得绝对路径
根据java.io.File的Doc文挡,可知:
默认情况下new File("/")代表的目录为:System.getProperty("user.dir")。
一下程序获得执行类的当前路径
 

 
  1. package org.cheng.file;  
  2.   
  3. import java.io.File;  
  4.   
  5. public class FileTest {  
  6.     public static void main(String[] args) throws Exception {  
  7.         System.out.println(Thread.currentThread().getContextClassLoader().getResource(""));  
  8.   
  9.         System.out.println(FileTest.class.getClassLoader().getResource(""));  
  10.   
  11.         System.out.println(ClassLoader.getSystemResource(""));  
  12.         System.out.println(FileTest.class.getResource(""));  
  13.         System.out.println(FileTest.class.getResource("/"));
  14.         //Class文件所在路径
  15.         System.out.println(new File("/").getAbsolutePath());  
  16.         System.out.println(System.getProperty("user.dir"));  
  17.     }  
  18. }  


4.2服务器中的Java类获得当前路径(来自网络)

(1).Weblogic

WebApplication的系统文件根目录是你的weblogic安装所在根目录。
例如:如果你的weblogic安装在c:eaweblogic700.....
那么,你的文件根路径就是c:.
所以,有两种方式能够让你访问你的服务器端的文件:
a.使用绝对路径:
比如将你的参数文件放在c:yourconfigyourconf.properties,
直接使用 new FileInputStream("yourconfig/yourconf.properties");
b.使用相对路径:
相对路径的根目录就是你的webapplication的根路径,即WEB-INF的上一级目录,将你的参数文件放

在yourwebappyourconfigyourconf.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

默认使用该方法的路径是:WEB-INF/classes。已经在Tomcat中测试。

5.读取文件时的相对路径,避免硬编码和绝对路径的使用。(来自网络)
5.1 采用Spring的DI机制获得文件,避免硬编码。
参考下面的连接内容:
http://www.javajia.net/viewtopic.php?p=90213&
5.2 配置文件的读取
参考下面的连接内容:
http://dev.csdn.net/develop/article/39/39681.shtm

5.3 通过虚拟路径或相对路径读取一个xml文件,避免硬编码

参考下面的连接内容:
http://club.gamvan.com/club/clubPage.jsp?iPage=1&tID=10708&ccID=8

6.Java中文件的常用操作(复制,移动,删除,创建等)(来自网络)
常用 java File 操作类
http://www.easydone.cn/014/200604022353065155.htm

Java文件操作大全(JSP中)
http://www.pconline.com.cn/pcedu/empolder/gj/java/0502/559401.html

java文件操作详解(Java中文网)
http://www.51cto.com/html/2005/1108/10947.htm

JAVA 如何创建删除修改复制目录及文件
http://www.gamvan.com/developer/java/2005/2/264.html

总结:
通过上面内容的使用,可以解决在Web应用服务器端,移动文件,查找文件,复制
删除文件等操作,同时对服务器的相对地址,绝对地址概念更加清晰。
建议参考URI,的RFC标准文挡。同时对Java.io.File. Java.net.URI.等内容了解透彻
对其他方面的理解可以更加深入和透彻。

 

 

 

 

 

 

 

 

 

 

 

 

第一种: 
File f = new File(this.getClass().getResource("/").getPath()); 
System.out.println(f); 
结果: 
C:\Documents%20and%20Settings\Administrator\workspace\projectName\bin 
获取当前类的所在工程路径; 
如果不加“/” 
File f = new File(this.getClass().getResource("").getPath()); 
System.out.println(f); 
结果: 
C:\Documents%20and%20Settings\Administrator\workspace\projectName\bin\com\test 
获取当前类的绝对路径; 

第二种: 
File directory = new File("");//参数为空 
String courseFile = directory.getCanonicalPath() ; 
System.out.println(courseFile); 
结果: 
C:\Documents and Settings\Administrator\workspace\projectName 
获取当前类的所在工程路径; 

第三种: 
URL xmlpath = this.getClass().getClassLoader().getResource("selected.txt"); 
System.out.println(xmlpath); 
结果: 
file:/C:/Documents%20and%20Settings/Administrator/workspace/projectName/bin/selected.txt 
获取当前工程src目录下selected.txt文件的路径 

第四种: 
System.out.println(System.getProperty("user.dir")); 
结果: 
C:\Documents and Settings\Administrator\workspace\projectName 
获取当前工程路径 

第五种: 
System.out.println( System.getProperty("java.class.path")); 
结果: 
C:\Documents and Settings\Administrator\workspace\projectName\bin 
获取当前工程路径

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

.如何获得当前文件路径

常用:

字符串类型: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"));
}
}

2.Web服务中

(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

(5).获得文件真实路径

string file_real_path=request.getRealPath("mypath/filename");

通常使用request.getRealPath("/");

3.文件操作的类

import java.io.*;
import java.net.*;
import java.util.*;
//import javax.swing.filechooser.*;
//import org.jr.swing.filter.*;

/**
* 此类中封装一些常用的文件操作。
* 所有方法都是静态方法,不需要生成此类的实例,
* 为避免生成此类的实例,构造方法被申明为private类型的。
* @since 0.1
*/

public class FileUtil {
/**
* 私有构造方法,防止类的实例化,因为工具类不需要实例化。
*/
private FileUtil() {

}

/**
* 修改文件的最后访问时间。
* 如果文件不存在则创建该文件。
* <b>目前这个方法的行为方式还不稳定,主要是方法有些信息输出,这些信息输出是否保留还在考

虑中。</b>
* @param file 需要修改最后访问时间的文件。
* @since 0.1
*/
public static void touch(File file) {
long currentTime = System.currentTimeMillis();
if (!file.exists()) {
System.err.println("file not found:" file.getName());
System.err.println("Create a new file:" file.getName());
try {
if (file.createNewFile()) {
// System.out.println("Succeeded!");
}
else {
// System.err.println("Create file failed!");
}
}
catch (IOException e) {
// System.err.println("Create file failed!");
e.printStackTrace();
}
}
boolean result = file.setLastModified(currentTime);
if (!result) {
// System.err.println("touch failed: " file.getName());
}
}

/**
* 修改文件的最后访问时间。
* 如果文件不存在则创建该文件。
* <b>目前这个方法的行为方式还不稳定,主要是方法有些信息输出,这些信息输出是否保留还在考

虑中。</b>
* @param fileName 需要修改最后访问时间的文件的文件名。
* @since 0.1
*/
public static void touch(String fileName) {
File file = new File(fileName);
touch(file);
}

/**
* 修改文件的最后访问时间。
* 如果文件不存在则创建该文件。
* <b>目前这个方法的行为方式还不稳定,主要是方法有些信息输出,这些信息输出是否保留还在考

虑中。</b>
* @param files 需要修改最后访问时间的文件数组。
* @since 0.1
*/
public static void touch(File[] files) {
for (int i = 0; i < files.length; i ) {
touch(files);
}
}

/**
* 修改文件的最后访问时间。
* 如果文件不存在则创建该文件。
* <b>目前这个方法的行为方式还不稳定,主要是方法有些信息输出,这些信息输出是否保留还在考

虑中。</b>
* @param fileNames 需要修改最后访问时间的文件名数组。
* @since 0.1
*/
public static void touch(String[] fileNames) {
File[] files = new File[fileNames.length];
for (int i = 0; i < fileNames.length; i ) {
files = new File(fileNames);
}
touch(files);
}

/**
* 判断指定的文件是否存在。
* @param fileName 要判断的文件的文件名
* @return 存在时返回true,否则返回false。
* @since 0.1
*/
public static boolean isFileExist(String fileName) {
return new File(fileName).isFile();
}

/**
* 创建指定的目录。
* 如果指定的目录的父目录不存在则创建其目录书上所有需要的父目录。
* <b>注意:可能会在返回false的时候创建部分父目录。</b>
* @param file 要创建的目录
* @return 完全创建成功时返回true,否则返回false。
* @since 0.1
*/
public static boolean makeDirectory(File file) {
File parent = file.getParentFile();
if (parent != null) {
return parent.mkdirs();
}
return false;
}

/**
* 创建指定的目录。
* 如果指定的目录的父目录不存在则创建其目录书上所有需要的父目录。
* <b>注意:可能会在返回false的时候创建部分父目录。</b>
* @param fileName 要创建的目录的目录名
* @return 完全创建成功时返回true,否则返回false。
* @since 0.1
*/
public static boolean makeDirectory(String fileName) {
File file = new File(fileName);
return makeDirectory(file);
}

/**
* 清空指定目录中的文件。
* 这个方法将尽可能删除所有的文件,但是只要有一个文件没有被删除都会返回false。
* 另外这个方法不会迭代删除,即不会删除子目录及其内容。
* @param directory 要清空的目录
* @return 目录下的所有文件都被成功删除时返回true,否则返回false.
* @since 0.1
*/
public static boolean emptyDirectory(File directory) {
boolean result = false;
File[] entries = directory.listFiles();
for (int i = 0; i < entries.length; i ) {
if (!entries.delete()) {
result = false;
}
}
return true;
}

/**
* 清空指定目录中的文件。
* 这个方法将尽可能删除所有的文件,但是只要有一个文件没有被删除都会返回false。
* 另外这个方法不会迭代删除,即不会删除子目录及其内容。
* @param directoryName 要清空的目录的目录名
* @return 目录下的所有文件都被成功删除时返回true,否则返回false。
* @since 0.1
*/
public static boolean emptyDirectory(String directoryName) {
File dir = new File(directoryName);
return emptyDirectory(dir);
}

/**
* 删除指定目录及其中的所有内容。
* @param dirName 要删除的目录的目录名
* @return 删除成功时返回true,否则返回false。
* @since 0.1
*/
public static boolean deleteDirectory(String dirName) {
return deleteDirectory(new File(dirName));
}

/**
* 删除指定目录及其中的所有内容。
* @param dir 要删除的目录
* @return 删除成功时返回true,否则返回false。
* @since 0.1
*/
public static boolean deleteDirectory(File dir) {
if ( (dir == null) || !dir.isDirectory()) {
throw new IllegalArgumentException("Argument " dir 
" is not a directory. ");
}

File[] entries = dir.listFiles();
int sz = entries.length;

for (int i = 0; i < sz; i ) {
if (entries.isDirectory()) {
if (!deleteDirectory(entries)) {
return false;
}
}
else {
if (!entries.delete()) {
return false;
}
}
}

if (!dir.delete()) {
return false;
}
return true;
}


/**
* 返回文件的URL地址。
* @param file 文件
* @return 文件对应的的URL地址
* @throws MalformedURLException
* @since 0.4
* @deprecated 在实现的时候没有注意到File类本身带一个toURL方法将文件路径转换为URL。
* 请使用File.toURL方法。
*/
public static URL getURL(File file) throws MalformedURLException {
String fileURL = "file:/" file.getAbsolutePath();
URL url = new URL(fileURL);
return url;
}

/**
* 从文件路径得到文件名。
* @param filePath 文件的路径,可以是相对路径也可以是绝对路径
* @return 对应的文件名
* @since 0.4
*/
public static String getFileName(String filePath) {
File file = new File(filePath);
return file.getName();
}

/**
* 从文件名得到文件绝对路径。
* @param fileName 文件名
* @return 对应的文件路径
* @since 0.4
*/
public static String getFilePath(String fileName) {
File file = new File(fileName);
return file.getAbsolutePath();
}

/**
* 将DOS/Windows格式的路径转换为UNIX/Linux格式的路径。
* 其实就是将路径中的"\"全部换为"/",因为在某些情况下我们转换为这种方式比较方便,
* 某中程度上说"/"比"\"更适合作为路径分隔符,而且DOS/Windows也将它当作路径分隔符。
* @param filePath 转换前的路径
* @return 转换后的路径
* @since 0.4
*/
public static String toUNIXpath(String filePath) {
return filePath.replace('\\', '/');
}

/**
* 从文件名得到UNIX风格的文件绝对路径。
* @param fileName 文件名
* @return 对应的UNIX风格的文件路径
* @since 0.4
* @see #toUNIXpath(String filePath) toUNIXpath
*/
public static String getUNIXfilePath(String fileName) {
File file = new File(fileName);
return toUNIXpath(file.getAbsolutePath());
}

/**
* 得到文件的类型。
* 实际上就是得到文件名中最后一个“.”后面的部分。
* @param fileName 文件名
* @return 文件名中的类型部分
* @since 0.5
*/
public static String getTypePart(String fileName) {
int point = fileName.lastIndexOf('.');
int length = fileName.length();
if (point == -1 || point == length - 1) {
return "";
}
else {
return fileName.substring(point 1, length);
}
}

/**
* 得到文件的类型。
* 实际上就是得到文件名中最后一个“.”后面的部分。
* @param file 文件
* @return 文件名中的类型部分
* @since 0.5
*/
public static String getFileType(File file) {
return getTypePart(file.getName());
}

/**
* 得到文件的名字部分。
* 实际上就是路径中的最后一个路径分隔符后的部分。
* @param fileName 文件名
* @return 文件名中的名字部分
* @since 0.5
*/
public static String getNamePart(String fileName) {
int point = getPathLsatIndex(fileName);
int length = fileName.length();
if (point == -1) {
return fileName;
}
else if (point == length - 1) {
int secondPoint = getPathLsatIndex(fileName, point - 1);
if (secondPoint == -1) {
if (length == 1) {
return fileName;
}
else {
return fileName.substring(0, point);
}
}
else {
return fileName.substring(secondPoint 1, point);
}
}
else {
return fileName.substring(point 1);
}
}

/**
* 得到文件名中的父路径部分。
* 对两种路径分隔符都有效。
* 不存在时返回""。
* 如果文件名是以路径分隔符结尾的则不考虑该分隔符,例如"/path/"返回""。
* @param fileName 文件名
* @return 父路径,不存在或者已经是父目录时返回""
* @since 0.5
*/
public static String getPathPart(String fileName) {
int point = getPathLsatIndex(fileName);
int length = fileName.length();
if (point == -1) {
return "";
}
else if (point == length - 1) {
int secondPoint = getPathLsatIndex(fileName, point - 1);
if (secondPoint == -1) {
return "";
}
else {
return fileName.substring(0, secondPoint);
}
}
else {
return fileName.substring(0, point);
}
}

/**
* 得到路径分隔符在文件路径中首次出现的位置。
* 对于DOS或者UNIX风格的分隔符都可以。
* @param fileName 文件路径
* @return 路径分隔符在路径中首次出现的位置,没有出现时返回-1。
* @since 0.5
*/
public static int getPathIndex(String fileName) {
int point = fileName.indexOf('/');
if (point == -1) {
point = fileName.indexOf('\\');
}
return point;
}

/**
* 得到路径分隔符在文件路径中指定位置后首次出现的位置。
* 对于DOS或者UNIX风格的分隔符都可以。
* @param fileName 文件路径
* @param fromIndex 开始查找的位置
* @return 路径分隔符在路径中指定位置后首次出现的位置,没有出现时返回-1。
* @since 0.5
*/
public static int getPathIndex(String fileName, int fromIndex) {
int point = fileName.indexOf('/', fromIndex);
if (point == -1) {
point = fileName.indexOf('\\', fromIndex);
}
return point;
}

/**
* 得到路径分隔符在文件路径中最后出现的位置。
* 对于DOS或者UNIX风格的分隔符都可以。
* @param fileName 文件路径
* @return 路径分隔符在路径中最后出现的位置,没有出现时返回-1。
* @since 0.5
*/
public static int getPathLsatIndex(String fileName) {
int point = fileName.lastIndexOf('/');
if (point == -1) {
point = fileName.lastIndexOf('\\');
}
return point;
}

/**
* 得到路径分隔符在文件路径中指定位置前最后出现的位置。
* 对于DOS或者UNIX风格的分隔符都可以。
* @param fileName 文件路径
* @param fromIndex 开始查找的位置
* @return 路径分隔符在路径中指定位置前最后出现的位置,没有出现时返回-1。
* @since 0.5
*/
public static int getPathLsatIndex(String fileName, int fromIndex) {
int point = fileName.lastIndexOf('/', fromIndex);
if (point == -1) {
point = fileName.lastIndexOf('\\', fromIndex);
}
return point;
}

/**
* 将文件名中的类型部分去掉。
* @param filename 文件名
* @return 去掉类型部分的结果
* @since 0.5
*/
public static String trimType(String filename) {
int index = filename.lastIndexOf(".");
if (index != -1) {
return filename.substring(0, index);
}
else {
return filename;
}
}
/**
* 得到相对路径。
* 文件名不是目录名的子节点时返回文件名。
* @param pathName 目录名
* @param fileName 文件名
* @return 得到文件名相对于目录名的相对路径,目录下不存在该文件时返回文件名
* @since 0.5
*/
public static String getSubpath(String pathName,String fileName) {
int index = fileName.indexOf(pathName);
if (index != -1) {
return fileName.substring(index pathName.length() 1);
}
else {
return fileName;
}
}

}
4.遗留问题

目前new FileInputStream()只会使用绝对路径,相对没用过,因为要相对于web服务器地址,比较麻烦

还不如写个配置文件来的快哪

5.按Java文件类型分类读取配置文件

配 置文件是应用系统中不可缺少的,可以增加程序的灵活性。java.util.Properties是从jdk1.2就有的类,一直到现在都支持load ()方法,jdk1.4以后save(output,string) ->store(output,string)。如果只是单纯的读,根本不存在烦恼的问题。web层可以通过 Thread.currentThread().getContextClassLoader().
getResourceAsStream("xx.properties") 获取;Application可以通过new FileInputStream("xx.properties");直接在classes一级获取。关键是有时我们需要通过web修改配置文件,我们不 能将路径写死了。经过测试觉得有以下心得:

1.servlet中读写。如果运用Struts 或者Servlet可以直接在初始化参数中配置,调用时根据servlet的getRealPath("/")获取真实路径,再根据String file = this.servlet.getInitParameter("abc");获取相对的WEB-INF的相对路径。
例:
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();

2.直接在jsp中操作,通过jsp内置对象获取可操作的绝对地址。
例:
// 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"); // 放在classes同级

OutputStream out = new FileOutputStream("abc.properties");

 

/**
    * 获取一个类的class文件所在的绝对路径。 这个类可以是JDK自身的类,也可以是用户自定义的类,或者是第三方开发包里的类。
    * 只要是在本程序中可以被加载的类,都可以定位到它的class文件的绝对路径。
    *
    * @param cls
    *             一个对象的Class属性
    * @return 这个类的class文件位置的绝对路径。 如果没有这个类的定义,则返回null。
    */
   public String getPathFromClass(Class cls) throws IOException {
     String path = null;
     if (cls == null) {
       throw new NullPointerException();
     }
     URL url = getClassLocationURL(cls);
     if (url != null) {
       path = url.getPath();
       if ("jar".equalsIgnoreCase(url.getProtocol())) {
         try {
           path = new URL(path).getPath();
         }
         catch (MalformedURLException e) {
         }
         int location = path.indexOf("!/");
         if (location != -1) {
           path = path.substring(0, location);
         }
       }
       File file = new File(path);
       path = file.getCanonicalPath();
     }
     return path;
   }

   /**
* 获取类的class文件位置的URL。这个方法是本类最基础的方法,供其它方法调用。
*/
private URL getClassLocationURL(final Class cls) {
   if (cls == null) {
     throw new IllegalArgumentException("class that input is null");
   }
   URL result = null;
   final String clsAsResource = cls.getName().replace('.', '/').concat(".class");
   final ProtectionDomain pd = cls.getProtectionDomain();
   if (pd != null) {
     final CodeSource cs = pd.getCodeSource();
     if (cs != null) {
       result = cs.getLocation();

     }
     if (result != null) {
       if ("file".equals(result.getProtocol())) {
         try {
           if (result.toExternalForm().endsWith(".jar")
               || result.toExternalForm().endsWith(".zip")) {
             result = new URL("jar:".concat(
                 result.toExternalForm()).concat("!/")
                              .concat(clsAsResource));
           }
           else if (new File(result.getFile()).isDirectory()) {
             result = new URL(result, clsAsResource);
           }
         }
         catch (MalformedURLException ignore) {
         }
       }
     }
   }

   if (result == null) {
     final ClassLoader clsLoader = cls.getClassLoader();
     result = clsLoader != null ? clsLoader.getResource(clsAsResource)
         : ClassLoader.getSystemResource(clsAsResource);
   }
   return result;
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Java中使用的路径,分为两种:绝对路径和相对路径。归根结底,Java本质上只能使用绝对路径来寻找资源。所有的相对路径寻找资源的方法,都不过是一些便利方法。不过是API在底层帮助我们构建了绝对路径,从而找到资源的!

 

在开发Web方面的应用时, 经常需要获取 服务器中当前WebRoot的物理路径。

 

如果是Servlet , Action , Controller, 或则Filter , Listener , 拦截器等相关类时, 我们只需要获得ServletContext, 然后通过ServletContext.getRealPath("/")来获取当前应用在服务器上的物理地址。

 

如果在类中取不到ServletContext时, 有两种方式可以做到:

 

1. 利用Java的类加载机制 调用 XXX.class.getClassLoader().getResource(""); 方法来获取到ClassPath , 然后处理获得WebRoot目录,这种方式只能是该class在WebRoot/WEB-INF/classes下才能生效, 如果该class被打包到一个jar文件中, 则该方法失效。这时就应该用下面一种方式。

 

2. spring框架的思路, 在WEB-INF/web.xml中 , 创建一个webAppRootKey的param, 指定一个值(默认为webapp.root)作为键值, 然后通过Listener , 或者Filter , 或者Servlet 执行String webAppRootKey = getServletContext().getRealPath("/"); 并将webAppRootKey对应的webapp.root 分别作为Key , Value写到System Properties系统属性中。之后在程序中通过System.getProperty("webapp.root")来获得WebRoot的物理路径。

 

根据第二种的思路,我们还可以再扩展一下。不过对于在部署在一台服务器中的应用来说,若还不是你所需请再往下看。

 

下面是一些得到classpath和当前类的绝对路径的一些方法。你可使用其中的一些方法来得到你需要的资源的绝对路径:

 

1. DebitNoteAction.class.getResource("")

 

得到的是当前类FileTest.class文件的URI目录。不包括自己!

 

如:file:/D:/eclipse/springTest/WebRoot/WEB-INF/classes/

 

atacarnet/src/com/evi/modules/atacarnet/action/

 

2. DebitNoteAction.class.getResource("/")

 

得到的是当前的classpath的绝对URI路径。

 

如:file:/D:/eclipse/springTest/WebRoot/WEB-INF/classes/

 

3. Thread.currentThread().getContextClassLoader().getResource("")

 

得到的也是当前ClassPath的绝对URI路径

 

如:file:/D:/eclipse/springTest/WebRoot/WEB-INF/classes/

 

4. DebitNoteAction.class.getClassLoader().getResource("") 或ClassLoader.getSystemResource("")

 

得到的也是当前ClassPath的绝对URI路径。

 

如:file:/D:/eclipse/springTest/WebRoot/WEB-INF/classes/

 

5. 取得服务器相对路径

 

System.getProperty("user.dir")

 

例如:E:\apache-tomcat-5.5.16\apache-tomcat-5.5.16\bin

 

我推荐使用Thread.currentThread().getContextClassLoader().getResource("")来得到当前的classpath的绝对路径的URI表示法

 

6. 取得项目中的绝对路径

 

一般用request.getRealPath("/")或request.getRealPath("/config/")

 

但现在不提倡使用request.getRealPath("/")了,大家可试用ServletContext.getRealPath("/")方法得到Web应用程序的根目录的绝对路径

 

要取得src的文件非常容易,因为src是默认的相对目录,比如你说要取得src下com目录的test.java文件,你只需要这样就够了

 

File f = new File(com/test.java);

 

但如果我要取得不在src目录或者WebRoot目录下的文件呢,而是要从src或者WebRoot同级的目录中取呢,比如说doc吧

 

我的硬方法是这样实现的:

 

String path = this.getServletContext().getRealPath("/");

 

Properties p = new Properties();

 

p.load(new FileInputStream(new File(path.substring(0,(path.lastIndexOf("\\WebRoot") + 1)) + "doc/db.properties")));

 

System.out.println(p.getProperty("driverName"));

 

原文链接:http://www.cn-java.com/www1/?action-viewnews-itemid-78354

 

 

 

但是我发现一个问题,就是当我用IO流访问web工程WEB-INF目录下的文件时,会报异常,告诉我相关文件找不到,不知道是什么原因?Mark

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

(1)、request.getRealPath("/");//不推荐使用获取工程的根路径 
(2)、request.getRealPath(request.getRequestURI());//获取jsp的路径,这个方法比较好用,可以直接在servlet和jsp中使用 
(3)、request.getSession().getServletContext().getRealPath("/");//获取工程的根路径,这个方法比较好用,可以直接在servlet和jsp中使用 
(4)、 this.getClass().getClassLoader().getResource("").getPath();//获取工程classes 下的路径,这个方法可以在任意jsp,servlet,java文件中使用,因为不管是jsp,servlet其实都是java程序,都是一个 class。所以它应该是一个通用的方法。

0、关于绝对路径和相对路径

1.基本概念的理解绝对路径:绝对路径就是你的主页上的文件或目录在硬盘上真正的路径,(URL和物理路径)例 如:C:xyz est.txt 代表了test.txt文件的绝对路径。http://www.sun.com/index.htm也代表了一个URL绝对路径。相对路径:相对与某个基 准目录的路径。包含Web的相对路径(HTML中的相对目录),例如:在Servlet中,"/"代表Web应用的跟目录。和物理路径的相对表示。例 如:"./" 代表当前目录,"../"代表上级目录。这种类似的表示,也是属于相对路径。另外关于URI,URL,URN等内容,请参考RFC相关文档标准。RFC 2396: Uniform Resource Identifiers (URI): Generic Syntax,(http://www.ietf.org/rfc/rfc2396.txt)2.关于JSP/Servlet中的相对路径和绝对路径。 2.1服务器端的地址服务器端的相对地址指的是相对于你的web应用的地址,这个地址是在服务器端解析的(不同于html和javascript中的相对 地址,他们是由客户端浏览器解析的)

1、request.getRealPath

方法:request.getRealPath("/") 
得到的路径:C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\strutsTest\

方法:request.getRealPath(".") 
得到的路径:C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\strutsTest\.

方法:request.getRealPath("") 
得到的路径:C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\strutsTest

request.getRealPath("web.xml") 
C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\strutsTest\web.xml

2、request.getParameter(""); 
    ActionForm.getMyFile();

方法:String filepath = request.getParameter("myFile"); 
得到的路径:D:\VSS安装目录\users.txt

方法:String filepath = ActionForm.getMyFile(); 
得到的路径:D:\VSS安装目录\users.txt

-------------------------------------------------- 
strutsTest 为工程名

myFile 在ActionForm中,为private String myFile; 
在jsp页面中:为<html:file property="myFile"></html:file>

--------------------------------------------------

3、获得系统路径

在Application中: 
System.getProperty("user.dir")

在Servlet中: 
ServletContext servletContext = config.getServletContext(); 
String rootPath = servletContext.getRealPath("/");

在jsp中: 
application.getRealPath("")

4、其他1

1.可以在servlet的init方法里

String path = getServletContext().getRealPath("/");

这将获取web项目的全路径

例如 :E:\eclipseM9\workspace\tree\

tree是我web项目的根目录

2.你也可以随时在任意的class里调用

this.getClass().getClassLoader().getResource("").getPath();

这将获取 到classes目录的全路径

例如 : /D:/workspace/strutsTest/WebRoot/WEB-INF/classes/

还有 this.getClass().getResource("").getPath().toString();

这将获取 到 /D:/workspace/strutsTest/WebRoot/WEB-INF/classes/bl/

这个方法也可以不在web环境里确定路径,比较好用

3.request.getContextPath();

获得web根的上下文环境

如 /tree

tree是我的web项目的root context

5、其他2

java获取路径几种途径- -

      1. jdk如何判断程序中的路径呢?一般在编程中,文件路径分为相对路径和绝对路径,绝对路径是比较好处理的,但是不灵活,因此我们在编程中对文件进行操作的时候,一般都是读取文件的相对路径,

相对路径可能会复杂一点,但是也是比较简单的,相对的路径,主要是相对于谁,可以是类加载器的路径,或者是当前 java文件下的路径,在jsp编程中可能是相对于站点的路径,相对于站点的路径,我们可以通过 getServletContext().getRealPath("\") 和request.getRealPath("\"):这个是取得站点的绝对路径; 而getContextPath():取得站点的虚拟路径;

      2. class.getClassLoader.getPath():取得类加载器的路径:什么是类加载器呢? 一般类加载器有系统的和用户自己定义的;系统的ClassLoader就是jdk提供的,他的路径就是jdk下的路径,或者在 jsp编程,比如Tomcat ,取得的类加载器的位置就是tomaca自己设计的加载器的路径,

明白了这些之后,对于文件路径的操作就会相当的清楚,我们在编程的时候,只要想清楚我们所操作的文件是相对于什么路径下的,取得相对路径就可以了.

6、总结

1、获取web服务器下的文件路径 
request.getRealPath("/") 
application.getRealPath("")【jsp中 】 
ServletContext().getRealPath("")

System.getProperty("user.dir")【不同位置调用,获取的路径是动态变化的】

2、获取本地路径

jsp中,<html:file property="myFile"/>

request.getParameter("myFile"); 
ActionForm.getMyFile(); 
获取的值相同:如D:\VSS安装目录\users.txt

*********************************

this.getClass().getClassLoader().getResource("").getPath(); 
==/D:/workspace/strutsTest/WebRoot/WEB-INF/classes/ 
this.getClass().getResource("").getPath().toString(); 
==/D:/workspace/strutsTest/WebRoot/WEB-INF/classes/bl/

3、获取相对路径

request.getContextPath();

如:/strutsTest

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

1、利用System.getProperty()函数获取当前路径:
System.out.println(System.getProperty("user.dir"));//user.dir指定了当前的路径

2、使用File提供的函数获取当前路径:
File directory = new File("");//设定为当前文件夹
try{
    System.out.println(directory.getCanonicalPath());//获取标准的路径
    System.out.println(directory.getAbsolutePath());//获取绝对路径
}catch(Exceptin e){}

File.getCanonicalPath()和File.getAbsolutePath()大约只是对于new File(".")new File("..")两种路径有所区别。

# 对于getCanonicalPath()函数,“."就表示当前的文件夹,而”..“则表示当前文件夹的上一级文件夹
# 对于getAbsolutePath()函数,则不管”.”、“..”,返回当前的路径加上你在new File()时设定的路径
# 至于getPath()函数,得到的只是你在new File()时设定的路径

比如当前的路径为 C:\test :
File directory = new File("abc");
directory.getCanonicalPath(); //得到的是C:\test\abc
directory.getAbsolutePath();    //得到的是C:\test\abc
direcotry.getPath();                    //得到的是abc

File directory = new File(".");
directory.getCanonicalPath(); //得到的是C:\test
directory.getAbsolutePath();    //得到的是C:\test\.
direcotry.getPath();                    //得到的是.

File directory = new File("..");
directory.getCanonicalPath(); //得到的是C:\
directory.getAbsolutePath();    //得到的是C:\test\..
direcotry.getPath();                    //得到的是..




另外:System.getProperty()中的字符串参数如下:

System.getProperty()参数大全
# java.version                                Java Runtime Environment version 
# java.vendor                                Java Runtime Environment vendor 
# java.vendor.url                           Java vendor URL 
# java.home                                Java installation directory 
# java.vm.specification.version   Java Virtual Machine specification version 
# java.vm.specification.vendor    Java Virtual Machine specification vendor 
# java.vm.specification.name      Java Virtual Machine specification name 
# java.vm.version                        Java Virtual Machine implementation version 
# java.vm.vendor                        Java Virtual Machine implementation vendor 
# java.vm.name                        Java Virtual Machine implementation name 
# java.specification.version        Java Runtime Environment specification version 
# java.specification.vendor         Java Runtime Environment specification vendor 
# java.specification.name           Java Runtime Environment specification name 
# java.class.version                    Java class format version number 
# java.class.path                      Java class path 
# java.library.path                 List of paths to search when loading libraries 
# java.io.tmpdir                       Default temp file path 
# java.compiler                       Name of JIT compiler to use 
# java.ext.dirs                       Path of extension directory or directories 
# os.name                              Operating system name 
# os.arch                                  Operating system architecture 
# os.version                       Operating system version 
# file.separator                         File separator ("/" on UNIX) 
# path.separator                  Path separator (":" on UNIX) 
# line.separator                       Line separator ("\n" on UNIX) 
# user.name                        User's account name 
# user.home                              User's home directory 
user.dir                               User's current working directory

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值