Gopal00005
Gopal00005

Reputation: 2151

How to get resource files from the runnable jar file which are in buildpath

I just need the files from jar file which are in resources directory at run time...

I know some ways just like...but it only reads images

ImageIO.read(Login.class.getResource("res/images/icon.png"));

Here I can read Images from the directory within JAR which is added to the build path in eclipse but here I am facing some issue while getting some ".so" file and some "cascade_hand.xml" file from resources/cascades/... , I need them at run time to be available from the runnable .JAR file.

I had tried this too..but this doesn't works..

CascadeClassifier cascade = new CascadeClassifier(
            "resources/cascades/haarcascade_mcs_leftear.xml");

nor this works...

CascadeClassifier cascade = new CascadeClassifier(this.getClass().getResourceAsStream("resources/cascades/haarcascade_mcs_leftear.xml");

I know there is way to copy that file in some temp directory and use them but I really don't know it how to do it ?

InputStream is = this.getClass().getResourceAsStream("resources/cascades/haarcascade_mcs_leftear.xml");

Is there any other way to access that type of files from Runnable JAR ?

I had also some issue in jar file created with eclipse.

Eclipse creates Runnable jar file and creates directories of resources directories within jar file which are in build path but, in real the all are created as one parent directory in jar file.

I have the folder hierarchy in eclipse is just like as following image.

enter image description here

Upvotes: 3

Views: 1998

Answers (2)

llogiq
llogiq

Reputation: 14511

Unfortunately, OpenCV does the file reading in native code, so the only way is to first copy the data to a temporary file.

String tempDir="tmp"; //TODO: use a sensible default
Path tmp = Files.createTempFile(tempDir, "cv");
Files.copy(Login.class.getResourceAsStream(
    "resources/cascades/haarcascade_mcs_leftear.xml"), tmp);
CascadeClassifier cascade = new CascadeClassifier(tmp.toString());

Upvotes: 2

m b
m b

Reputation: 310

You can use a classloader for reading the file

InputStream inn = ClassLoader
            .getSystemResourceAsStream("resources/cascades/haarcascade_mcs_leftear.xml");

Hope it helps.

Upvotes: 0

Related Questions