当我使用相对路径时,我可以从 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 的路径
您可以获取该类的 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();
and use jar.getName()
获取要解析的路径以获取您的安装目录。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)