Java获取各种绝对路径的8种方法

Java sxdgy 90℃

示例代码如下:

public class GetPath extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //第1种:获取服务器二进制命令路径
        String path1 = new File("").getCanonicalPath();
        System.out.println("path1:" + path1);

        //第2种:获取服务器二进制命令路径
        String path2 = System.getProperty("user.dir");
        System.out.println("path2:" + path2);

        //第3种:获取项目的根目录
        String path3 = getServletContext().getRealPath("");
        System.out.println("path3:" + path3);

        //第4种:获取项目的根目录,但Servlet2.1以后已过期
        String path4 = request.getRealPath("");
        System.out.println("path4:" + path4);

        //第5种:获取类加载的根路径
        String path5 = Thread.currentThread().getContextClassLoader().getResource("").getPath();
        System.out.println("path5:" + path5);

        //第6种:获取类加载的根路径
        String path6 = this.getClass().getClassLoader().getResource("").getPath();
        System.out.println("path6:" + path6);

        //第7种:获取类加载的根路径
        String path7 = this.getClass().getResource("/").getPath();
        System.out.println("path7:" + path7);

        //第8种:获取当前类的路径
        String path8 = this.getClass().getResource("").getPath();
        System.out.println("path8:" + path8);
    }
}

运行结果:

path1:D:\java\apache-tomcat-8.5.37\bin
path2:D:\java\apache-tomcat-8.5.37\bin
path3:D:\ROOT\
path4:D:\ROOT\
path5:/D:/ROOT/WEB-INF/classes/
path6:/D:/ROOT/WEB-INF/classes/
path7:/D:/ROOT/WEB-INF/classes/
path8:/D:/ROOT/WEB-INF/classes/com/gqzzw/

转载请注明:零五博客 » Java获取各种绝对路径的8种方法

喜欢 (0)or分享 (0)