Java获取项目中路径方法
假设项目结构如下:D:\workspace\maven-web-project\target\maven-web-project\|-WEB-INF\ |-classes\ |-pack\ |-Test.class |-config.properties
class Test { static { /*在Test类中获取路径*/ // 打印 file:/D:/workspace/maven-web-project/target/maven-web-project/WEB-INF/classes/ System.out.println(Test.class.getClassLoader().getResource("")); // 打印 file:/D:/workspace/maven-web-project/target/maven-web-project/WEB-INF/classes/ System.out.println(Test.class.getClassLoader().getResource("/")); // 打印 file:/D:/workspace/maven-web-project/target/maven-web-project/WEB-INF/classes/pack/ System.out.println(Test.class.getResource("")); // 打印 file:/D:/workspace/maven-web-project/target/maven-web-project/WEB-INF/classes/ System.out.println(Test.class.getResource("/")); // 打印 D:\App\apache-tomcat-7.0.69\bin System.out.println(new File("").getAbsolutePath()); // 打印 D:\ System.out.println(new File("/").getAbsolutePath()); // 打印 null System.out.println(Thread.currentThread().getClass().getResource("")); // 打印 file:/D:/App/apache-tomcat-7.0.69/lib/ System.out.println(Thread.currentThread().getClass().getResource("/")); // 打印 file:/D:/App/apache-tomcat-7.0.69/lib/ System.out.println(Thread.currentThread().getClass().getClassLoader().getResource("")); // 打印null System.out.println(Thread.currentThread().getClass().getClassLoader().getResource("/")); }}
总结:
获取classpath的方法Test.class.getClassLoader().getResource("")Test.class.getResource("/")
欢迎加入学习交流群569772982,大家一起学习交流。