James T. James T. - 1 year ago 52
Java Question

Is there a way to get the file path of the .java file executed or compiled?

In Python the global variable

is the full path of the current file.

seems to return the path of the current working directory.

I want to get the path of the current .java, .class or package file.

Then use this to get the path to an image.

My project file structure in Netbeans looks like this: files

Update to use code suggested from my chosen best answer:

// read image data from picture in package
try {
InputStream instream = TesseractTest.class

bufferedImage = ImageIO.read(instream);
catch (IOException e) {

This code is used in the usage example from tess4j.

My full code of the usage example is here.

Answer Source

If you want to load an image file stored right next to your class file, use Class::getResourceAsStream(String name).

In your case, that would be:

try (InputStream instream = TesseractTest.class.getResourceAsStream("eurotext.tif")) {
    // read stream here

This assumes that your build system copies the .tif file to your build folder, which is commonly done by IDEs, but requires extra setup in build tools like Ant and Gradle.

If you package your program to a .jar file, the code will still work, again assuming your build system package the .tif file next to the .class file.