我正在尝试使用以下方法查找正在运行的 jar 文件的位置:
File jarFile = new File(JarPath.class.getProtectionDomain().getCodeSource().getLocation().toURI());
当我在 IDE (eclipse) 上运行它时,它会返回正确的路径。 但是当我将 jar 作为可执行文件运行时,返回的代码源是
rsrc:./
关于如何获得正确路径的想法?
最佳答案
尝试不同的方法来获取位置。
String jarFilePath = ClassLoader.getSystemClassLoader().getResource(".")
.toURI()
.getPath()
.replaceFirst("/", "");
这会让您到达 jar 文件的父位置。
C:/Users/Roshana Pitigala/Desktop/
您仍然需要添加文件名和扩展名 (jarFileName.jar
)。
关于java - Myclass.class.getProtectionDomain().getCodeSource() 返回空路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32050178/