我正在Netbeans中使用Maven创建一个联系人应用程序。对于程序的操作,我希望用户在文件夹/avatars中添加和存储图像(联系人化身),并在侦听器事件中访问它们。我可以从ProjectRoot/src/main/resources/映像目录中访问图像,但不能访问ProjectRoot/avatars。注意:我不想将avatars存储在资源目录中,因为它们将在程序操作期间被用户添加。
我尝试过使用getClass().getResource(avatarPath);正如类似问题中所建议的那样,但它没有起作用。我还尝试将"avatars“目录添加到POM中,作为它自己的资源目录,但这也不起作用。
如何在使用Maven?时访问项目根目录中的文件/文件夹
listviewContacts.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<Contact>() {
@Override
public void changed(ObservableValue<? extends Contact> observable, Contact oldValue, Contact newValue) {
String avatar = newValue.getAvatar();
String avatarPath = null;
if (avatar.isEmpty()) {
avatarPath = "/images/" + DEFAULT_AVATAR; // loads from ProjectRoot/src/main/resources/images
} else {
avatarPath = "/avatars/" + avatar; // won't load from ProjectRoot/avatars
}
try {
imageviewContact.setImage(new Image(avatarPath));
} catch (IllegalArgumentException ex) {
System.err.println("Could not locate " + avatarPath);
}
}
});
发布于 2018-08-10 04:59:52
问题在于理解javafx.scene.image.Image的不同构造器从哪里开始它们的路径。
当为图像使用URL构造函数时,URL路径将从Maven的定义资源文件夹 (/src/main/resources或添加到pom.xml文件中的任何其他资源目录)开始:
// the supplied string invokes the URL constructor
Image image = new Image("path/to/file");
当对图像使用InputStream构造函数(通过FileInputStream)时,路径将从项目/应用程序的根目录开始:
// the FileInputStream invokes the InputStream constructor
Image image = new Image(new FileInputStream("path/to/file"));
发布于 2018-08-08 13:06:49
你混合了两个不同的东西。
您可以将类路径资源与类一起打包在jarfile中,也可以在将java显式添加到java类路径的目录中(使用-cp命令行参数)。可以通过getClass().getResource访问。
也可以使用从任意位置加载文件。然后,您的"projectRoot“是文件系统中的某个文件夹,您可以硬编码、配置=C:/projectRoot/with/file,或者使用一些相对路径。Maven与此无关,因为avatars“将在程序操作期间被用户添加”。
您的用户不会启动IDE,对吗?
https://stackoverflow.com/questions/51746929
复制相似问题