java路径问题总结

1 在SSH各个层次获得项目根目录 REQUEST 等
	System.out.println(ServletActionContext.getServletContext().getRealPath("/"));
System.out.println(Struts2Utils.getParameter("loginName"));

利用了STRUTS2的ServletActionContext类
他是线程安全的 使用了threadlocal

或者利用springside的Struts2Utils类
他封装了struts2的ServletActionContext类

2 JSP页面中取得项目的根目录
<c:set var="ctx" value="${pageContext.request.contextPath}"/>  

JSP取得服务器根目录
<%=application.getRealPath("/")%>
<%=pageContext.getServletContext().getRealPath("")%>
<%=pageContext.getServletContext().getRealPath("/")%>

D:\eclipse_workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp1\wtpwebapps\swp\
D:\eclipse_workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp1\wtpwebapps\swp
D:\eclipse_workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp1\wtpwebapps\swp\
<%=application.getRealPath("/")%>等同于<%=pageContext.getServletContext().getRealPath("/")%>
因为application = pageContext.getServletContext()

3 file取路径
    // 默认情况下,java.io 包中的类总是根据当前用户目录来解析相对路径名。  
        // 此目录由系统属性 user.dir 指定,通常是 Java 虚拟机的调用目录  
        System.out.println(System.getProperty("user.dir"));  
        File f = new File("");  
        String absolutePath = f.getAbsolutePath();  
        System.out.println(absolutePath);  
        System.out.println(FileUtils.readFileToString(new File(  
               "src/test/java/io/aa.txt")));//源文件的路径  
       System.out.println(Thread.currentThread().getContextClassLoader()  
           .getResource("")); 


4 Class.getResourceAsStream 和 ClassLoader.getResourceAsStream区别
引用

基本上,两个都可以用于从 classpath 里面进行资源读取,  classpath包含classpath中的路径
和classpath中的jar。
两个方法的区别是资源的定义不同, 一个主要用于相对与一个object取资源,而另一个用于取相对于classpath的
资源,用的是绝对路径。
在使用Class.getResourceAsStream 时, 资源路径有两种方式, 一种以 / 开头,则这样的路径是指定绝对
路径, 如果不以 / 开头, 则路径是相对与这个class所在的包的。
在使用ClassLoader.getResourceAsStream时, 路径直接使用相对于classpath的绝对路径。
举例,下面的三个语句,实际结果是一样的:
   com.explorers.Test.class.getResourceAsStream("abc.jpg")
= com.explorers.Test.class.getResourceAsStream("/com/explorers/abc.jpg")
= ClassLoader.getResourceAsStream("com/explorers/abc.jpg")


5 取服务器下的文件
<%@page import="org.apache.commons.io.IOUtils"%>
<%InputStream is = application.getResourceAsStream("/demo.htm");
out.println(IOUtils.toString(is));%>



你可能感兴趣的:(java,eclipse,jsp,虚拟机,ssh)