java - 奇怪的 Java 问题 : can find one file with short filepath but cannot find another

标签 java file

我正在开发一个 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/

相关文章:

java - Java 中的过程/工作流

java - Hibernate针对简单查询和海量数据的性能提升

java - 检查 Java 中所有文件句柄何时被释放

java - 即使有 NoSuchFileException ? Java(尝试在启动窗口上添加文件)

java - 将 Object 类型转换为 JButton 类型?

java - 将 INFO 和 ERROR 日志与 java.util.logging 分开

java - 相同的 Action 处理程序,多个按钮

c# - 在 C# 中缓存二进制文件

c++ - 使用指向文件的指针从 vector 中保存对象

android - 以编程方式在android中创建一个pdf文件并写入其中