简体   繁体   English

具有完整路径的getResourceAsStream(String)返回null,但是文件存在

[英]getResourceAsStream(String) with full path returns null but file exists

Well I'm realy at a loss here. 好吧,我真的很茫然。 I try some JOGL and want to get a texture on an Object. 我尝试一些JOGL,并希望在Object上获得纹理。 I usually do it like this: 我通常这样做:

Texture[] thumbs = new Texture[pics.length];

try {
    for (int i = 0; i < thumbs.length; i ++){
        InputStream stream = getClass().getResourceAsStream(pics[i].getPath());
        data = TextureIO.newTextureData(stream, false, "jpg");
        thumbs[i] = TextureIO.newTexture(data);
    }
} catch (IOException e) {
    e.printStackTrace();
}

Usually this works fine if the jpg-file is in the source-directory but this time the file lies elsewhere and I recieve an IOException that says the stream was null . 通常,如果jpg文件位于源目录中,则此方法可以正常工作,但这次文件位于其他位置,并且我收到一个IOException ,该IOException表示流为null

pics[i].getPath() returns this String: C:\\beispieluser\\bjoern\\eigene_bilder\\eckelsheim.jpg . pics[i].getPath()返回以下字符串: C:\\beispieluser\\bjoern\\eigene_bilder\\eckelsheim.jpg This is the exact path where the file lies. 这是文件所在的确切路径。 Can somebody tell me where my thoughts took the wrong turn? 有人可以告诉我我的想法错了吗?

getResourceAsStream() and friends will only open "classpath resources", which are files that appear on the classpath along with your compiled classes. getResourceAsStream()和朋友只会打开“类路径资源”,它们是与已编译类一起出现在类路径上的文件。 To open that file, use new File() or (on Java 7) Files.newInputStream() . 要打开该文件,请使用new File()或(在Java 7上) Files.newInputStream()

getResourceAsStream() finds resources that are in the classpath. getResourceAsStream()查找类路径中的资源。 I'm pretty sure it won't work for an absolute path somewhere else on your disk. 我很确定它不能在磁盘上其他位置的绝对路径下工作。

  1. You files folder is not a part of your classpath. 您的文件文件夹不是您的类路径的一部分。 You can add it, but i don't think it proper way for resources like images to be a part of classpath. 您可以添加它,但是我不认为像图像这样的资源成为classpath的一部分是正确的方法。
  2. Use FileInputStream: 使用FileInputStream:

Code: 码:

try{
    for (int i = 0; i < thumbs.length; i ++){
      File file = new File(pics[i].getPath());
      FileInputStream stream = new FileInputStream(file);
      data = TextureIO.newTextureData(stream, false, "jpg");
      thumbs[i] = TextureIO.newTexture(data);
    }
} catch (IOException e) {
   e.printStackTrace();
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM