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获取。