Sunday 30 November 2014

Starting a new Process programmatically from Java

Background

In this post we will see how we can run any process from java programmatically. In specific I will show how can we compile a java file from a Java process. We can very well use Runtime.getRuntime().exec() method to start the process but in this post I am going to demonstrate using ProcessBuilder class.

Code

    public static void executeJavacCommand() throws IOException {

        List<String> paramsExecute = new ArrayList<String>();
        paramsExecute.add("C:\\Program Files\\Java\\jdk1.6.0_31\\bin\\javac.exe");
        paramsExecute.add("-cp");
        paramsExecute.add(".");
        paramsExecute.add("HelloWorld.java");
        ProcessBuilder pBuilder = new ProcessBuilder(paramsExecute);
        Process process = pBuilder.start();
        Reader reader = new InputStreamReader(process.getErrorStream());
        int ch;
        while((ch = reader.read())!= -1)
            System.out.print((char)ch);
        reader.close();

    }

Note1 : In above code I am only printing the error stream of the process but you can manipulate the output stream as well as provide input stream to the process.
Note 2:  You can also see my previous post on how to get the java executable paths. You can programmatically derive those and use it in above code.


Related Links

Finding Java home programatically from Java program

Background

There might be various scenarios in which you might need to get the path of java executable. For example to lets say start java program from withing Java code. In this post we will see how can we achieve that. I will demonstrate a method to find the JAVA_HOME that is usually the JDK directory. Once you have that it is easy to get executable. For eg javac will be in JAVA_HOME/bin/javac.exe

Code

public class JavaHomeTest{

    public static void main(String args[]) throws IOException {
        System.out.println(getJDKDir());
    }

    public static String getJDKDir() {
        File javaHome = new File( System.getProperty( "java.home" ) ).getParentFile();
        File jdkDirectory = null;
        if( javaHome.getName().contains( "jdk" ) ) { 
            //happens in IntelliJ
            jdkDirectory = javaHome;
        } else { 
            //General Scenario - eclipse / command line
            File[] childDirs = javaHome.listFiles();
            for(File file : childDirs) {
                if(file.getName().contains("jdk")) {
                    jdkDirectory = file;
                    break;
                }
            }
            
        }
        return jdkDirectory.getAbsolutePath();
    }

}


Output : 

I am running Windows. The output that I get is 'C:\Program Files (x86)\Java\jdk1.7.0_55'. Code is same for Linux as well. You will get your Java directory.

t> UA-39527780-1 back to top