Execute external program in java

sqtd picture sqtd · Dec 21, 2012 · Viewed 148.7k times · Source

I tried to make an application that calls an external program that I have to pass two parameters. It doesn't give any errors.The program.exe,written in c++, takes a picture and modifies the content of txt file. The java program runs but it does nothing

Here is my sample code

    String[] params = new String [3];
    params[0] = "C:\\Users\\user\\Desktop\\program.exe";
    params[1] = "C:\\Users\\user\\Desktop\\images.jpg";
    params[2] = "C:\\Users\\user\\Desktop\\images2.txt";
    Runtime.getRuntime().exec(params);

Answer

Steven picture Steven · Dec 21, 2012

borrowed this shamely from here

Process process = new ProcessBuilder("C:\\PathToExe\\MyExe.exe","param1","param2").start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;

System.out.printf("Output of running %s is:", Arrays.toString(args));

while ((line = br.readLine()) != null) {
  System.out.println(line);
}

More information here

Other issues on how to pass commands here and here