James T. James T. - 2 months ago 6
Java Question

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

In Python the global variable

__file__
is the full path of the current file.

System.getProperty("user.dir");
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
.getResourceAsStream("eurotext.tif");

bufferedImage = ImageIO.read(instream);
}
catch (IOException e) {
System.out.println(e.getMessage());
}


This code is used in the usage example from tess4j.

My full code of the usage example is here.

Answer

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.