我正在开发一个 Java Swing 应用程序,我正在其中读取多个图形文件以填充基于图 block 的 map 编辑器。
我通过使用名为 TileSet 的类来创建我的这些平铺 View 对象,该类本质上将我的图像分解为单独的文件。代码本身可以工作,但我的文件路径有一个问题,这让我摸不着头脑。这是发生的事情,
TileSelector ts = new TileSelector(new TileSet("src\\resources\\minecraft.png"));
MapView mapView = new MapView(new TileSet("src\\resources\\mapviewdefault.png"));
由于某种原因,我的 TileSelector 接受我将目录写入它将使用的图像的格式,但 MapView 抛出 IOException(找不到文件!)。这两个文件都在这个目录中,我真正能想到的唯一区别是一个图像比另一个大得多,其中最小的图像加载没有问题。如果我把完整的目录放到更大的图像中,它就可以工作,但是由于我正在为一个学校项目编写这个程序,该项目将提供给赞助商,所以我不能保留这种格式作为我交付包的最终方式。
有什么想法吗?
此外,这是我的 TileSet 的代码,根据我的堆栈跟踪,问题正在发生......
private void createTileSet(String fileName) {
try {
File file = new File(fileName);
if (!file.exists())
throw new IOException("File not found...");
image = ImageIO.read(new File(fileName));
numTilesWidth = image.getWidth() /tileWidth; //Set how many tiles on the X axis there are
numTilesHeight = image.getHeight() / tileHeight; //Set how many tiles on the Y axis there are
numTiles = numTilesHeight * numTilesWidth;
for (int h = 0; h < numTilesHeight; h++) {
for (int w = 0; w < numTilesWidth; w++) {
imagesList.add(image.getSubimage(w * tileWidth, h * tileHeight, tileWidth, tileHeight));
}
}
} catch (IOException e) {
System.out.println("IOException catch: " + e);
e.printStackTrace();
}
}
最佳答案
src
路径在运行时(构建和打包应用程序时)将不存在,并且您永远不应该在代码中引用它。 resources
目录中的资源将无法作为磁盘上的普通File
进行访问,因为它们不是,它们通常是 jar 文件中的条目.
相反,您需要使用Class#getResource
来定位加载资源...类似...
image = ImageIO.read(getClass().getResource(fileName));
你应该使用类似...的方式来调用它
TileSelector ts = new TileSelector(new TileSet("/resources/minecraft.png"));
MapView mapView = new MapView(new TileSet("/resources/mapviewdefault.png"));
您应该避免在代码中使用 \\
,因为它不跨平台兼容,一般可以使用 /
,如果您确实想要,请使用 File.separator
改为
关于java - 奇怪的 Java 问题 : can find one file with short filepath but cannot find another,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27467405/