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