1.在eclipse中测试
Demo:
/**
* 2020年2月25日上午10:33:41
*/
package testGetPaths;
/**
* @author XWF
*
*/
public class TestGetPaths {
/**
* @param args
*/
public static void main(String[] args) {
//通过系统属性集合获得用户当前工作目录
String userDir = System.getProperty("user.dir");
System.out.println("System获取路径:" + userDir);
//通过class的classLoader
String loaderPath = TestGetPaths.class.getClassLoader().getResource("").getPath();
System.out.println("classLoader获取路径:" + loaderPath);
//通过class的resource
String resourcePath = TestGetPaths.class.getResource("").getPath();
System.out.println("resourcePath获取路径:" + resourcePath);
//通过Thread
String threadPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
System.out.println("thread获取路径:" + threadPath);
}
}
eclipse执行结果:
2.打成jar包测试
编写java文件TestGetPaths.java
public class TestGetPaths{
public static void main(String[] args){
//通过系统属性集合获得用户当前工作目录
String userDir = System.getProperty("user.dir");
System.out.println("System获取路径:" + userDir);
//通过class的classLoader
String loaderPath = TestGetPaths.class.getClassLoader().getResource("").getPath();
System.out.println("classLoader获取路径:" + loaderPath);
//通过class的resource
String resourcePath = TestGetPaths.class.getResource("").getPath();
System.out.println("resourcePath获取路径:" + resourcePath);
//通过Thread
String threadPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
System.out.println("thread获取路径:" + threadPath);
}
}
编写manifest.mf文件(注意Main-Class下面要空一行)
Manifest-Version: 1.0
Class-Path: .
Main-Class: TestGetPaths
编译:
javac -encoding UTF-8 .\TestGetPaths.java
打包:
jar cvfm test.jar .\manifest.mf .\TestGetPaths.class
执行:
java -jar .\test.jar
结果: