我正在尝试使用InputStream加载图像。但是,当我加载图像时,它总是返回null。这是我的项目结构:
project
--+ src
----+ chess
------+ model
--------+ piece
----------+ Piece.java
------+ assets
--------+ icons
----------+ piece
------------+ rook_black.png
我用来访问图像的路径是:./src/chess/assets/icons/piece/rook_black.png
我试图显示Piece.java
中该目录中的所有文件都有效:
String path = "./src/chess/assets/icons/piece/";
File[] files = new File(path).listFiles();
for (File file: files) {
System.out.println(file.getName());
}
我的实际代码是:
public Image getImage() {
String path = "./src/chess/assets/icons/piece/rook_black.png";
InputStream image = getClass().getResourceAsStream(path);
if (image != null) {
return new Image(image);
}
System.out.println("No " + toString() + " image in " + path);
return null;
}
此代码实际上输出了No rook image in ./src/chess/assets/icons/piece/rook_black.png
,但我希望InputStream不为空。