开发者

loadResourceasStream from a subfolder of the project java

I am sure it's a basic question , I just can't figure it out I am trying to load bunch of images located in images subfolder of my project

here is my code

package com.ieml.swt.diploma;

import java.io.InputStream;



public class loadTest
{


    public static void main(String[] args) 
    {

System.out.println(getResourceImage("marks.png"));
    }


    public static InputStream getResourceImage(String fileName) {

        return loadTest.class.getResourceAsStream(开发者_如何学C"./images/" + fileName);
    }
}

I have a separe folders for src and class files so .java file is located in src/com/ieml/swt/diploma folder and .class file under bin/com/ieml/swt/diploma folder

files I'm trying to load here do existt in the "loadTest/images" subfolder loadTest is my project's root directory it justs print s null like it's doesn't load this file am I missing something here ?


loadTest.class.getResourceAsStream("./images/" + fileName);

This will look for the images under bin/com/ieml/swt/diploma/images, i.e. relative to the .class file. If you leave out the dot in the beginning, it will look in bin/images.

But whatever you do, Class.getResourceAsStream() is for loading resources from the classpath, i.e. inside the bin folder. There is no way to access anything outside, and it wouldn't make much sense anyway, since it's designed to work for JAR files as well. Usually, you actually put the resources in the src folder and copy them to bin during the build (eclipse will do this automatically).


The getResourceAsStream() method loads classpath resources. Is the images directory in your classpath?


I believe Class.getResourceAsStream will take paths relative to the location of the class file, in your case the classes/com/ieml/swt/diploma folder. You may want to try

  loadTest.class.getClassLoader().getResourceAsStream("../images/" + filename);

I assume that your images folder is on the same level as your bin or classes folder. The basic idea is that you can get a resource by a relative path from your classloader root (your classpath root).

This is not always a good idea but since this looks like a school project I don't think that would be an issue.


Depending on what you're trying to do, this may not be the right way to go about it. getResourceAsStream is commonly used to load icons from a jar on the classpath. If you're just trying to get a hold of an image on disk for some reason, take a look at the static methods on javax.imageio.ImageIO: http://download.oracle.com/docs/cd/E17409_01/javase/6/docs/api/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜