carget
carget

Reputation: 77

Accessing Jar Dependencies

I have a jar file that contains an exe and banner image (jpg) that the entire script depends on. How can I access and use these 2 dependencies from itself (the jar file)? Currently the jpg is accessed by:

BufferedImage getBanner = ImageIO.read(new File("banner.jpg"));
JLabel drawBanner = new JLabel(new ImageIcon(getBanner));

and the exe is accessed by:

String cmd = "exe [params]";
Runtime run = Runtime.getRuntime();
Process pr = run.exec(cmd);

I might even host the banner image online and just have it pull it from there, so I can dynamically update that.

Upvotes: 2

Views: 122

Answers (1)

jayunit100
jayunit100

Reputation: 17648

The Classloader for the jre can "find" any file in your classpath.

To add an external program, so that its accessible to your jar :

First create a class loader and use your ClassLoader to get the resource dynamically, and let it handle the path specific details of the file location. Thus ... you will do something like this :

URL myExecutable = 
        MyClass.class.getClassLoader().getResource("executable/program.exe");

Now, you should be able to DIRECTLY access the program , as if it is any other file.

File f=new File(myExecutable.toURI());

And now you can call it using

Runtime.getRuntime().exec(f.getAbsolutePath());

CAVEAT

At this point, ask yourself WHY AM I BUNDLING AN EXE IN A JAR FILE ? Better to have a separate package for each operating system platform, in a zip file. Put the jar and the exe in a zip file --- rather than bundling the OS specific executable to your java binary.

Upvotes: 2

Related Questions