简体   繁体   中英

Why am I getting a file not found exception here?

This is driving me nuts, I used both concatenation and format and while the strings produced match the correct paths. the loop throws exceptions from the get go.

what's going on?

ImageIcon thisWorks= new ImageIcon(testview.class.getResource("/led_images/"+1+"_off.png"));
    for(int i = 1; i <= 10; i++)
    {
        String on = String.format("/led_images/%d_on.png",i);
        String off = String.format("/led_images/%d_off.png",i);


    ledIcons.put( i+"_off", new ImageIcon(testview.class.getResource(off)));
    ledIcons.put( i+"_on", new ImageIcon(testview.class.getResource(on)));
    }

Edit: am I using Map incorrectly? It's a Map<String,ImageIcon> one.

Edit2: Yeah I guess I'm using the map incorrectly.

I have it declared like this:

public Map< String, ImageIcon> ledIcons;

It's a null value inside the loop. So I guess it's not like c++ then?

Edit3: Yeah, nevermind this question, I didn't initialize the field properly, my apologies.

If thisWorks works, then obviously "/led_images/1_off.png" exists. If you get exceptions for the images in the loop, then perhaps one of

/led_images/2_off.png
/led_images/2_off.png
/led_images/3_off.png
...
/led_images/10_off.png

/led_images/1_on.png
/led_images/2_on.png
/led_images/3_on.png
...
/led_images/10_on.png

are missing.

Edit: am I using Map incorrectly? It's a Map one.

No, that looks fine to me. (Unless you have a problem with the retrieval later on.)

I'm guessing that the leading slash is the problem; you probably want a relative path. See the docs:

http://download.oracle.com/javase/6/docs/api/java/lang/Class.html#getResource(java.lang.String )

Initialize the field:

public Map< String, ImageIcon> ledIcons = new HashMap< String, ImageIcon>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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