java獲得當前路徑下的絕對路徑的方法。或者某一文件的絕對路徑
import java.net.URL;
import java.security.CodeSource;
import java.security.ProtectionDomain;
public class TestPath {
public static void main(String[] args) {
ProtectionDomain domain = TestPath.class.getProtectionDomain();
CodeSource codeSource = domain.getCodeSource();
URL location = codeSource.getLocation();
String path = location.getPath();
System.out.println(path);
URL url = TestPath.class.getClassLoader().getResource("log4j.xml");
String aurl = url.getPath();
System.out.println(aurl);
URL pathUrl = TestPath.class.getResource("");
System.out.println(pathUrl.getPath());
}
}
主要有兩種,都是通過當前class獲取。