0

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?

skaffman
  • 398,947
  • 96
  • 818
  • 769
Russell
  • 795
  • 11
  • 18

2 Answers2

3

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"

Rocky
  • 941
  • 7
  • 11
0

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());
        }
    }
Kuldeep Jain
  • 8,409
  • 8
  • 48
  • 73
  • @Russell, Ah you wanted to execute a JAR file from within your code. I thought you want to extract its content. Got the question after it was edited by skaffman – Kuldeep Jain Feb 01 '12 at 10:06