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

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

使用System.getProperty("user.dir")方法获取当前工作目录的绝对路径。这个路径通常是运行Java程序时所在的目录。

String projectPath = System.getProperty("user.dir");
System.out.println(projectPath);

使用Class.getResource()方法获取类所在的路径。这个路径是相对于类所在的包的路径。

String projectPath = MyClass.class.getResource("").getPath();
System.out.println(projectPath);

使用ClassLoader.getResource()方法获取类加载器所在的路径。这个路径是相对于类加载器的根路径。

ClassLoader classLoader = MyClass.class.getClassLoader();
String projectPath = classLoader.getResource("").getPath();
System.out.println(projectPath);

使用ServletContext.getRealPath()方法获取Web应用的根路径。这个路径是Web容器运行时动态计算的。

ServletContext servletContext = getServletContext();
String projectPath = servletContext.getRealPath("/");
System.out.println(projectPath);

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

阅读剩余
THE END