3

When I run my jar file, i get a javax.imageio.IIOException: Can't read input file!

But the file is in the jar!

the code:

try {imgs.put("player1" , ImageIO.read(new File("/car1.png")));}
    catch (IOException e)   {System.out.println(e);}

I have tried to put car1.png everywhere in the jar file but its not working.

Nishant
  • 54,584
  • 13
  • 112
  • 127
Faleidel
  • 33
  • 1
  • 3
  • 1
    I don't know much about jars but your code there might be looking for `car1.png` in `/` instead of `/path/to/jar/car1.png` because your filename is "/car1.png", not "car1.png". – jamesbtate Mar 25 '11 at 03:26
  • 2
    possible duplicate of [Java Swing: Displaying images from within a Jar](http://stackoverflow.com/questions/31127/java-swing-displaying-images-from-within-a-jar) – Brian Roach Mar 25 '11 at 03:29
  • 3
    Please use the search before asking questions. – Brian Roach Mar 25 '11 at 03:29

1 Answers1

3

You probably want to do this instead.

InputStream is = getClass().getResourceAsStream("car1.png");
ImageIO.read(is); 
CoolBeans
  • 20,654
  • 10
  • 86
  • 101
  • "You probably want to do this instead." Yes. The basic problem with the OP's approach is that a File object cannot be established to a resource in a Jar file. There is a variant of the command that returns an URL e.g. `URL urlToResource = getClass().getResource("car1.png");`. Most methods that accept a File will also accept either an InputStream or URL. – Andrew Thompson Mar 25 '11 at 04:51