Java 如何访问位于我的项目上方目录中的文件
Java how to access a file sitting in the directory above my project
我设法找到了一些与此类似的主题,但到目前为止没有一个与这个问题完全匹配。我正在制作一个 JavaFX 应用程序,用户可以在其中添加要在应用程序中显示的图像。这些图像作为文件路径字符串存储在文本文件数据库中。由于 .jar 文件是只读的,我无法将图像直接添加到项目中,因此我创建了一个资产文件夹,该文件夹位于图像全部所在的项目之外。
所以文件夹结构是:
-> 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 打破你的罐子,你可以使用 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
}
就是否是个好主意而言,您的图像存储取决于当前工作目录,这有点糟糕。在我看来,您应该使用用户主目录 (System.getProperty("user.home")
) 的点前缀子文件夹来存储您的应用程序数据
我设法找到了一些与此类似的主题,但到目前为止没有一个与这个问题完全匹配。我正在制作一个 JavaFX 应用程序,用户可以在其中添加要在应用程序中显示的图像。这些图像作为文件路径字符串存储在文本文件数据库中。由于 .jar 文件是只读的,我无法将图像直接添加到项目中,因此我创建了一个资产文件夹,该文件夹位于图像全部所在的项目之外。
所以文件夹结构是:
-> 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 打破你的罐子,你可以使用 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
}
就是否是个好主意而言,您的图像存储取决于当前工作目录,这有点糟糕。在我看来,您应该使用用户主目录 (System.getProperty("user.home")
) 的点前缀子文件夹来存储您的应用程序数据