Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java:运行JAR文件时如何获取文件路径_Java - Fatal编程技术网

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

Java:运行JAR文件时如何获取文件路径,java,Java,当我使用相对路径时,我可以从Eclipse运行Java程序。但是,当我将其作为JAR文件运行时,该路径不再有效。在我的src/components/SettingsWindow.java中,我有: ObjectInputStream ois=newobjectinputstream(newfileinputstream(“./src/files/profile.ser”) 我得到一个FileNotFoundException 我的文件目录如下所示: 我所尝试的: String filePath

当我使用相对路径时,我可以从Eclipse运行Java程序。但是,当我将其作为JAR文件运行时,该路径不再有效。在我的src/components/SettingsWindow.java中,我有:

ObjectInputStream ois=newobjectinputstream(newfileinputstream(“./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放在
新的FileInputStream(filePath)
中,但这些都不起作用,我仍然得到一个FileNotFoundException。当我
System.out.println(filePath)
它说:files/profile.ser


当我在src/components/SettingsWindow.java中时,我正在尝试获取src/files/profile.ser的路径。您可以获取该类的URL:

字符串路径=
String.join(“/”,getClass().getName().split(Pattern.quote(“.”))
+“.class”;
URL URL=getClass().getResource(“/”+路径);
这将产生“file:/path/to/package/class.class”或“jar:/path/to/jar.jar!/package/class.class”。您可以使用URL,也可以使用

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

并使用
jar.getName()
获取要解析的路径以获取安装目录。

获取我使用的当前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
替换?