Java:运行JAR文件时如何获取文件路径 [英] Java: How to get path of a file when running JAR file
问题描述
使用相对路径时,可以从Eclipse运行Java程序.但是当我将其作为JAR文件运行时,该路径不再起作用.在我的src/components/SettingsWindow.java中,我有:
When I use relative path, I can run my Java program from Eclipse. But when I run it as a JAR file, the path doesn't work anymore. In my src/components/SettingsWindow.java I have:
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("./src/files/profile.ser"));
我收到FileNotFoundException.
I get a FileNotFoundException.
我的文件目录如下:文件目录
我尝试过的事情:
字符串filePath = this.getClass().getResource("/files/profile.ser").toString();
字符串filePath = this.getClass().getResource("/files/profile.ser").getPath();
字符串filePath = this.getClass().getResource("/files/profile.ser").getFile().toString();
然后我将filePath放在新的FileInputStream(filePath)中,但是这些都不起作用,我仍然收到FileNotFoundException.当我 System.out.println(filePath)
时,它说:files/profile.ser
And I'd just put filePath in new FileInputStream(filePath)
but none of these work and I still get a FileNotFoundException. When I System.out.println(filePath)
it says: files/profile.ser
当我在src/components/SettingsWindow.java中时,我试图获取src/files/profile.ser的路径
I'm trying to get the path of src/files/profile.ser while I'm in src/components/SettingsWindow.java
推荐答案
您可以获取该类的URL:
You can get the URL to the class:
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或使用
which will either yield "file:/path/to/package/class.class" or "jar:/path/to/jar.jar!/package/class.class". You either can work with the URL or use
JarFile jar =
((JarURLConnection) url.openConnection()).getJarFile();
并使用 jar.getName()
获取解析路径以获取安装目录.
and use jar.getName()
to get the path to parse to get your installation directory.
这篇关于Java:运行JAR文件时如何获取文件路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!