I have been trying to get the following code to work.
package com.compressor;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
public class JSCompressor {
public static void main(String[] args) {
try {
String currentDir = System.getProperty("user.dir");
String[] commands = { "java", "-jar","yuicompressor.jar"};
ProcessBuilder pb = new ProcessBuilder(commands);
pb.directory(new File(currentDir));
Process p = pb.start();
BufferedReader output = new BufferedReader(new InputStreamReader(p.getInputStream()));
System.out.println("Result : " + output.readLine());
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
My project directory looks like what is shown in the image below :
But still when I run the program inside eclipse it gives me null output like given below :
Result : null
I have tried googling several options without any success. Could anyone please point out what I am doing wrong here ?.
I the jar I am testing is indeed runnable and gives an output when run normally in the command line. But I need to be able to run this jar programetically. Could anyone please help ?.
I think you want to change
String[] commands = { "java", "-jar","yuicompressor.jar"};
to
String[] commands = { "java", "-jar", jarPath};
Since that's the path to your yuicompressor.jar
. Also, you should use another thread to read the process output - and wait for the process to complete.
final Process p = pb.start();
// then start a thread to read the output.
new Thread(new Runnable() {
public void run() {
BufferedReader output = new BufferedReader(
new InputStreamReader(p.getInputStream()));
String line;
System.out.print("Result : ");
while ((line = output.readLine()) != null) {
System.out.println(line);
}
}
}).start();
p.waitFor();