【问题标题】:Unable to Read Local Resource无法读取本地资源
【发布时间】:2013-06-17 06:34:16
【问题描述】:

我有一个项目(在 Eclipse 中,但这没关系),其层次结构如下:

-src
---Start.java
---resources
-----media
-------intro.wav
-----textures
-------logo.png
-------tiles.abotm

Start.java 中,我尝试使用Class.getResourceAsStream(String)tiles.abotm 作为输入流:

public class Start
{
  public static void main(String[] args)
  {
    try
    {
      InputStream in = Start.class.getResourceAsStream(
                           "/resources/textures/tiles.abotm");
    }catch(Exception e){
      e.printStackTrace();
    }
  }
}

够简单吧?抱歉不行。 InputStream 完全为空,大小为 0。我还尝试将 FileInputStream 直接打开到tiles.abotm 的绝对位置,但我得到了同样的结果!我知道文件不是空的。事实上,根据 Windows、Eclipse 和用于创建前面提到的 FileInputStream 的 File 对象,它有 2,257 个字节。同样根据File对象,它是可读的,可写的,它存在,它不是一个目录,它的名字是tiles.abotm。那么,如果 File 对象可以读取,为什么不能在 InputStream 中打开呢??

--编辑-- 我忘了提到我在textures 目录中有另一个文件,名为logo.png,我可以以完全相同的方式打开和读取它,完全没有问题。只有这个文件。

--回复fge,实际代码如下: Loader.loadTextureMap("/resources/textures/tiles.abotm");//这个在单独的类中的单独方法中调用。

public class Loader{
  public static TextureMap loadTextureMap(String texMap){
    DataInputStream dis = new DataInputStream(
                 Start.class.getResourceAsStream(texMap));
    //It then goes on to read it, but I've determined that at this point,
                there is nothing in this DataInputStream.
  }
}

【问题讨论】:

  • 当你说“绝对位置”时,你的意思是从/开始吗?
  • 我相信 Eclipse 要求它的资源存在于资源文件夹而不是源文件夹中。您可以尝试使用 /src/resources/textures/tiles.abotm 之类的东西作为测试,但我会在您发布之前进行更改
  • 旁注:.getResourceAsStream() 永远不会抛出异常;如果资源不存在,则返回null
  • 各位,请看一下编辑。

标签: java io stream


【解决方案1】:

经过大量讨论,适用于 OP 的代码:

final byte[] buf = new byte[1024]; // or other
final URL url = Start.class.getResource("whatever");
// check for url == null

InputStream in;
ByteArrayOutputStream out;

// I really wish this syntax was something else, it sucks
try (
    in = url.openStream();
    out = new ByteArrayOutputStream();
) {
    int count;
    while ((count = in.read(buf)) != -1)
        out.write(buf, 0, count);
    out.flush();
} catch (IOException e) {
    // handle e here
}

final ByteBuffer buffer = ByteBuffer.wrap(out.toByteArray());
// use the buffer

【讨论】:

  • 我这样做了,它成功了,但是,这个文件将被打包在 jar 中。所以,我不能在结局节目中那样阅读它。
  • 好的,你如何构建纹理贴图的东西?
  • 我已经制作了自己的程序来这样做。这一切都基于我自己的可序列化对象版本(称为 BSOs - 基本可序列化对象),所有这个文件都是两个整数和一个图像。是这个问题吗?一开始的字节值 0 是否搞砸了?因为,在这个文件中,前 8 个字节是 0 0 0 16 0 0 0 16。
  • 非常感谢!有效!现在,我的问题是,为什么它不能以另一种方式工作?
  • 好问题!现在我不知道......我没有使用DataInputStream for ages,因为我现在系统地使用 NIO ;)
猜你喜欢
  • 2012-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-28
  • 2021-01-27
  • 2011-10-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多