Myclass.class.getProtectionDomain().getCodeSource()返回空路径

Ido*_*doS 6 java eclipse jvm path executable-jar

我正在尝试使用以下方法查找正在运行的jar文件的位置:

File jarFile = new File(JarPath.class.getProtectionDomain().getCodeSource().getLocation().toURI());
Run Code Online (Sandbox Code Playgroud)

当我在IDE(eclipse)上运行它时,它返回正确的路径.但是当我将jar作为可执行文件运行时,返回的代码源是

rsrc:./
Run Code Online (Sandbox Code Playgroud)

关于如何获得正确路径的想法?

Ros*_*ala 3

尝试不同的方法来获取位置。

String jarFilePath = ClassLoader.getSystemClassLoader().getResource(".")
        .toURI()
        .getPath()
        .replaceFirst("/", "");
Run Code Online (Sandbox Code Playgroud)

这将为您提供 jar 文件的父位置。

C:/Users/Roshana Pitigala/Desktop/
Run Code Online (Sandbox Code Playgroud)

您仍然需要添加文件名和扩展名 ( jarFileName.jar)。