我设法找到了一些与此类似的主题,但到目前为止没有任何主题完全匹配这个问题。我正在制作一个 JavaFX 应用程序,用户可以在其中添加要在应用程序中显示的图像。这些图像作为文件路径字符串存储在文本文件数据库中。由于 .jar 文件是只读的,我无法将图像直接添加到项目中,因此我不得不创建一个位于图像全部所在项目外部的 Assets 文件夹。
所以文件夹结构是:
-> Parent Folder that the .jar file sits in
- Project Folder or .jar file
- src
* classes.java
- assets Folder
* image.jpg
* image2.png
现在,我知道如果我的 imagePath
位于项目文件夹内,Image image = new Image(getClass().getResourceAsStream(imagePath));
将起作用。但我需要文件夹的相对路径(以及外部)。
我的第一个(也是目前最重要的)问题是如何声明完全脱离应用程序文件夹的相对路径?
其次,这是好的做法吗?如果正在制作 JavaFX 应用程序并希望添加要与该应用程序一起存储的新图像,是否有更好的方法?
最佳答案
所以利用Getting the Current Working Directory in Java要打破你的jar,你可以使用FileInputStream
s来获取你的Image
s。例如
String cwd = System.getProperty("user.dir");
File dirAboveCws = new File(cwd).getParentFile();
File[] imageFiles = dirAboveCws.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return !pathname.getName().contains("jpg");
}
});
for (File imageFile : imageFiles) {
FileInputStream fileInputStream = new FileInputStream(imageFile);
Image image = ImageIO.read(fileInputStream); // Here is your image
}
至于这是否是个好主意,图像存储依赖于当前工作目录有点糟糕。 IMO 您应该使用用户主目录的点前缀子文件夹 (System.getProperty("user.home")
) 来存储您的应用程序数据
关于Java如何访问位于我的项目上方目录中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47803479/