`

Java获取路径的方法

    博客分类:
  • J2SE
阅读更多

路径问题是Java开发过程中最常出现的问题之一。

现在对其中常见的几类进行一下总结归纳:

 

public class PathTest1 {
  public static void main(String[] args) {
   new PathTest1().test();
  }
  void test() {
   System.out.println(this.getClass().getClassLoader().getResource(".").getPath());
   System.out.println(this.getClass().getResource("").getPath());
   System.out.println(this.getClass().getResource(" ").getPath());
   System.out.println(this.getClass().getResource("/").getPath());
  }
}

执行结果,如下: 

 /E:/workspace/MyLife/bin/
 /E:/workspace/MyLife/bin/path/
 /E:/workspace/MyLife/bin/path/%20
 /E:/workspace/MyLife/bin/

 ‘20%’是对空格‘ ’的十六位编码,如果路径中有汉字,当然也会进行编码。

   路径前的斜杠,是为了适应Unix系统绝对路径的格式。

 

 

    工程(项目)所在的绝对路径:

System.out.println(System.getProperty("user.dir"));

   结果: E:\workspace\MyLife

 

工程(项目)的classpath(一般不止一个):

System.out.println(System.getProperty("java.class.path"));

 结果:E:\workspace\MyLife\bin;E:\workspace\MyLife\spring-core-2.5.6.jar;E:\workspace\MyLife\spring-quartz.jar;E:\workspace\MyLife\commons-logging.jar;...

一个系统发布路径,和当前classpath路径。

 

 

 

servlet的路径(这位仁兄写得很好,转载一下):http://www.blogjava.net/limq/archive/2005/03/01/1600.aspx

Servlet 路径

首先建立一个测试页面:path.jsp

<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage="" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>无标题文档</title>
</head>

<body>
请求服务器:
<%= request.getServerName() %><br>
使用协议:
<%= request.getProtocol() %><br>
请求方法:
<%= request.getMethod() %><br>
请求断口号:
<%= request.getServerPort() %><br>
Context路径:
<%= request.getContextPath() %><br>
Servlet路径:
<%= request.getServletPath() %><br>
URI路径:
<%= request.getRequestURI() %><br>
查询字串:
<%= request.getQueryString() %><br>
<br>
使用者主機IP:
<%= request.getRemoteAddr() %><br>

<%= request.getRemotePort() %>
</body>
</html>

 

再用一下方式测试:
http://localhost:8080/WebModule1/path.jsp?name=justin&nick=caterpillar

结果为:
请求服务器: localhost
使用协议: HTTP/1.1
请求方法: GET
请求断口号: 8080
Context路径: /WebModule1
Servlet路径: /path.jsp
URI路径: /WebModule1/path.jsp
查询字串: name=justin&nick=caterpillar

使用者主?CIP: 127.0.0.1
1490

0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics