Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Locating default root folder for an Eclipse project

Tags:

java

file

eclipse

I am reading 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 do not know where to place my file to make the Eclipse IDE, and my project can detect it when I run my code.

Is there a better way of creating a BufferedImage from an image file stored in your project directory?

like image 561
Jonathan Avatar asked Jan 01 '26 18:01

Jonathan


2 Answers

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.

like image 151
Wayne Beaton Avatar answered Jan 03 '26 12:01

Wayne Beaton


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

like image 35
tangens Avatar answered Jan 03 '26 12:01

tangens



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!