Java在不同环境下获取当前路径的方法--this.getClass().getResource("")

  1. 在Servlet\Filter等Servlet web环境中,只要获得javax.servlet.ServletContext类型,则可以通过 getRealPath(“…”) 获得路径。相对路径中最顶层目录可通过参数“”/“”获取。
    request.getSession().getServletContext().getRealPath(“/“);

    2. JSP自定义标签javax.servlet.jsp.tagext.TagSupport
    ((javax.servlet.ServletContext)pageContext).getRealPath(“”);


    3. 普通Java Class对象文件中使用:
    this.getClass().getResource(“???”);
    如果Class文件在顶层目录(包)中,且“???”为空白字符串(“”””),及此方法在jar文件中执行则会返回null。在顶层目录(包)以下的各层目录(包)则会返回包含协议的URL。各层文件夹(包)之间使用“/”分隔。


    项目位置:D:\BeyondTrack–reference\jBPMWebDesigner

    javacode 位置:D:\BeyondTrack–reference\jBPMWebDesigner\build\web\classes\net\java\dev\beyondtrack\web\workflow\designer\japplet


    文件位置:D:\BeyondTrack–reference\jBPMWebDesigner\src\java\net\java\dev\beyondtrack\web\workflow\designer\icon



    /
     
    To change this template, choose Tools | Templates
      and open the template in the editor.
     
    /
    package net.java.dev.beyondtrack.web.workflow.designer.japplet;

    import javax.swing.ImageIcon;

    /*
     

      @author pub32
     
    /
    public class NewMain {

     public NewMain () {
      System.out.println(this.getClass().getResource(“”));
      System.out.println(this.getClass().getResource(“.”));
      System.out.println(this.getClass().getResource(“..”));
      System.out.println(this.getClass().getResource(“/“));
      System.out.println(this.getClass().getResource(“point.png”));
      System.out.println(this.getClass().getResource(“/point.png”));
      System.out.println(this.getClass().getResource(“./point.png”));
      System.out.println(this.getClass().getResource(“../point.png”));
      System.out.println(this.getClass().getResource(“icon/point.png”));
      System.out.println(this.getClass().getResource(“/icon/point.png”));
      System.out.println(this.getClass().getResource(“./icon/point.png”));
      System.out.println(this.getClass().getResource(“../icon/point.png”));
     }

     public static void main(String[] args) {
      System.out.println(“====== Test.class ======”);
      NewMain test = new NewMain();
     }
    }



    ====== Test.class ======
    file:/D:/BeyondTrack–reference/jBPMWebDesigner/build/web/WEB-INF/classes/net/java/dev/beyondtrack/web/workflow/designer/japplet/
    file:/D:/BeyondTrack–reference/jBPMWebDesigner/build/web/WEB-INF/classes/net/java/dev/beyondtrack/web/workflow/designer/japplet/
    file:/D:/BeyondTrack–reference/jBPMWebDesigner/build/web/WEB-INF/classes/net/java/dev/beyondtrack/web/workflow/designer/
    file:/D:/BeyondTrack–reference/jBPMWebDesigner/build/web/WEB-INF/classes/
    null
    null
    null
    null
    null
    null
    null
    file:/D:/BeyondTrack–reference/jBPMWebDesigner/build/web/WEB-INF/classes/net/java/dev/beyondtrack/web/workflow/designer/icon/point.png
    BUILD SUCCESSFUL (total time: 0 seconds)