Linux 拨号vps windows公众号手机端

Java获取项目路径的多种方式

lewis 7年前 (2018-12-02) 阅读数 8 #程序编程
文章标签 Java

在Java中,可以通过多种方式获取项目路径:

  1. 使用System.getProperty("user.dir")方法获取当前工作目录的绝对路径。这个路径通常是运行Java程序时所在的目录。
String projectPath = System.getProperty("user.dir");
System.out.println(projectPath);
  1. 使用Class.getResource()方法获取类所在的路径。这个路径是相对于类所在的包的路径。
String projectPath = MyClass.class.getResource("").getPath();
System.out.println(projectPath);
  1. 使用ClassLoader.getResource()方法获取类加载器所在的路径。这个路径是相对于类加载器的根路径。
ClassLoader classLoader = MyClass.class.getClassLoader();
String projectPath = classLoader.getResource("").getPath();
System.out.println(projectPath);
  1. 使用ServletContext.getRealPath()方法获取Web应用的根路径。这个路径是Web容器运行时动态计算的。
ServletContext servletContext = getServletContext();
String projectPath = servletContext.getRealPath("/");
System.out.println(projectPath);

注意:以上方法中获取的路径都是字符串,可以根据需要进行进一步的处理。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门