Java:如何在运行JAR文件时获取文件路径

4
当我使用相对路径时,我可以从Eclipse中运行我的Java程序。但是当我将其作为JAR文件运行时,路径不再起作用了。在我的src/components/SettingsWindow.java中,我有以下代码: ObjectInputStream ois = new ObjectInputStream(new FileInputStream("./src/files/profile.ser")); 我得到了一个FileNotFoundException。
我的文件目录如下: 文件目录 我尝试过以下方法: String filePath = this.getClass().getResource("/files/profile.ser").toString(); String filePath = this.getClass().getResource("/files/profile.ser").getPath(); String filePath = this.getClass().getResource("/files/profile.ser").getFile().toString(); 然后我把filePath放在new FileInputStream(filePath)中,但是这些方法都不起作用,我仍然得到FileNotFoundException。当我执行System.out.println(filePath)时,它显示:files/profile.ser 我想在src/components/SettingsWindow.java中获取src/files/profile.ser的路径。
2个回答

1
您可以获得该类的URL:
        String path =                                                           
            String.join("/", getClass().getName().split(Pattern.quote(".")))    
            + ".class";                                                         
        URL url = getClass().getResource("/" + path);

这将返回 "file:/path/to/package/class.class" 或者 "jar:/path/to/jar.jar!/package/class.class"。你可以使用URL或者使用它。

            JarFile jar =                                                       
                ((JarURLConnection) url.openConnection()).getJarFile();

使用 jar.getName() 来获取路径,以解析出您的安装目录。


0

我使用以下代码获取当前JAR文件路径:

public static String getJarFilePath() throws FileNotFoundException {
    String path = getClass().getResource(getClass().getSimpleName() + ".class").getFile();
    if(path.startsWith("/")) {
        throw new FileNotFoundException("This is not a jar file: \n"+path);
    }
    if(path.lastIndexOf("!")!=-1) path = path.substring(path.lastIndexOf("!/")+2, path.length());
    path = ClassLoader.getSystemClassLoader().getResource(path).getFile();

    return path.substring(0, path.lastIndexOf('!')).replaceAll("%20", " ");
}

你能否编辑答案并提供一些解释性的注释,例如为什么需要if测试和%20替换? - andrewJames

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接