Javaパスの取得方法


パスの問題は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%'はスペース'''の16ビット符号化であり、パスに漢字があれば当然符号化される.
   パス前のスラッシュは、Unixシステムの絶対パスのフォーマットに適応するためです.
 
 
    プロジェクトが存在する絶対パス:
System.out.println(System.getProperty("user.dir"));

   結果:E:workspaceMyLife
 
プロジェクトのclasspath(一般的には1つだけではありません):
System.out.println(System.getProperty("java.class.path"));

 結果:E:workspaceMyLifebin;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
サーブレットパス
まずテストページを作成します: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パス:/WebModule 1サーブレットパス:/path.jspURIパス:/WebModule 1/path.jspクエリー文字列:name=justin&nick=caterpillar使用者主?CIP: 127.0.0.11490