I assume that you want to run the phantomjs executable from Java code.
You need to first find out the full path to the command you want to execute, in your case, phantomjs. If you downloaded zip, this is the directory into which you unzipped the file, where you see the phantomjs.exe executable file. If you downloaded it through the package manager to find out the full path from the terminal:
which phantomjs
Something like
/usr/bin/phantomjs
After that, you will need to use the Runtime class, which, among other things, allows you to run commands directly on the OS using exec. What you run will be treated as a Process , which you can use to read the output of the command.
A quick example without any exception handling that you MUST do.
Process process = Runtime.getRuntime().exec("/usr/bin/phantomjs myscript.js"); int exitStatus = process.waitFor(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader (process.getInputStream())); String currentLine=null; StringBuilder stringBuilder = new StringBuilder(exitStatus==0?"SUCCESS:":"ERROR:"); currentLine= bufferedReader.readLine(); while(currentLine !=null) { stringBuilder.append(currentLine); currentLine = bufferedReader.readLine(); } System.out.println(stringBuilder.toString());
Be sure to do the correct error handling, as you are creating an external interface for the JVM that the JVM does not precisely control, and can cause problems for the rest of your program if you cope with errors poorly.
source share