4

I'm a second year student just starting to pick up Java. I have this bit of code and it keeps throwing the exception:

try
{
    masterFish = ImageIO.read(getClass().getResource("fish1.gif"));
} 
catch (IOException iOException)
{
    iOException.printStackTrace();
}

Could someone explain the fish1.gif part? Am I supposed to have an image called fish1.gif downloaded somewhere?

spenibus
  • 4,339
  • 11
  • 26
  • 35
frostyshadows
  • 65
  • 1
  • 4

2 Answers2

1

See this question: Loading resources using getClass().getResource()

The getResource() method of getClass() will attempt to find a resource using the class file (.class extension) as a reference point. Thus your file should be located at the same place the class file is. For instance if your class is com.example.MyClass, your "fish1.gif" file should be located in the directory <>/src/com/example.

It is often considered bad style to mix resources and source code, so you might want to create a directory "resources" at the root of your project, place the resources there in a suitable hierarchy, and access them in a centralized way.

Community
  • 1
  • 1
ThBB
  • 66
  • 2
0

It most likely can't find "fish1.gif". Make sure when you compile your code, that "fish1.gif" is in the same directory as your "MAIN CLASS". Or instead of just "fish1.gif" you can write specifically where it is located on your hard-drive... Example: "C:/Users/name/Desktop/fish1.gif".

MainHeader
  • 21
  • 2