views:

430

answers:

4

I am attempting to read a file as follows:

File imgLoc = new File("Player.gif");

BufferedImage image = null;


try{
  image = ImageIO.read(imgLoc);
 }
 catch(Exception ex)
 {
  System.out.println("Image read error");
  System.exit(1);
 }
 return image;

I have a file named "Player.gif" as shown in imgLoc, but I do not know where to put the file. Where will eclipse look to find the file when I attempt to read it?

Edit: Also, is there a better way of creating a BufferedImage from an image file stored somewhere amongst the project directories? (IE. A better way of reading an image than through File, or a better method within File to create a BufferedImage)

A: 

Are you trying to write a plugin for eclipse or is it a regular project?

In the latter case, wouldn't that depend on where the program is installed and executed in the end?

While trying it out and running it from eclipse, I'd guess that it would find the file in the project workspace. You should be able to find that out by opening the properties dialog for the project, and looking under the Resource entry.

Also, you can add resources to a project by using the Import menu option.

Hope this helps.

Mikael Ohlson
A: 

from my experience it seems to be the containing projects directory by default, but there is a simple way to find out:

System.out.println(new File(".").getAbsolutePath());
pstanton
+1  A: 

In the run dialog you can choose the directory. The default is the project root.

tangens
+1  A: 

Take a look in the comments for Class.getResource and Class.getResourceAsStream. These are probably what you really want to use as they will work whether you are running from within the directory of an Eclipse project, or from a JAR file after you package everything up.

You use them along the lines of:

InputStream in = MyClass.class.getResourceAsStream("Player.gif");

In this case, Java would look for the file "Player.gif" next to the MyClass.class file. That is, if the full package/class name is "com.package.MyClass", then Java will look for a file in "[project]/bin/com/package/Player.gif". The comments for getResourceAsStream indicate that if you lead with a slash, i.e. "/Player.gif", then it'll look in the root (i.e. the "bin" directory).

Note that you can drop the file in the "src" directory and Eclipse will automatically copy it to the "bin" directory at build time.

HTH

Wayne Beaton