Russell
Russell

Reputation: 805

how do you execute .JAR files within java

How do you execute a JAR file within your source code?

I know that for an exe, you use

try
{
 Runtime rt = Rintime.getRuntime() ;
 Process p = rt.exec("Program.exe") ;
 InputStream in = p.getInputStream() ;
 OutputStream out = p.getOutputStream ();
 InputSream err = p,getErrorStram() ;

//do whatever you want
 //some more code

 p.destroy() ;
}catch(Exception exc){/*handle exception*/}

Is it the same only:

rt.exec("program.exe") changes to rt.jar("program.jar") or is it something different?

Upvotes: 0

Views: 1014

Answers (2)

Kuldeep Jain
Kuldeep Jain

Reputation: 8598

You can use java.util.jar.JarFile API to read the content of jar file. Following is the code sample of how to use it to extract a file from a jar file:

    File jar = new File("Your_Jar_File_Path")
    final JarFile jarFile = new JarFile(jar);
    for (final Enumeration<JarEntry> files = jarFile.entries(); files.hasMoreElements();)
    {
        final JarEntry file = files.nextElement();
        final String fileName = file.getName();
        final InputStream inputStream = jarFile.getInputStream(file);
        ........
        while (inputStream.available() > 0)
        {
            yourFileOutputStream.write(inputStream.read());
        }
    }

Upvotes: 0

Rocky
Rocky

Reputation: 951

In order to extract a jar file instead of exec("program.exe") you need to say

exec("<path to jar command> -xf program.jar") 

Usually the jar command is available in your bin directory and if the env variables are properly set , you can even say exec("jar -xf program.jar")

For running the jar file you can say "java -jar program.jar"

Upvotes: 3

Related Questions