Skip to content

Instantly share code, notes, and snippets.

@digizeph
Created February 5, 2014 08:17
Show Gist options
  • Select an option

  • Save digizeph/8819201 to your computer and use it in GitHub Desktop.

Select an option

Save digizeph/8819201 to your computer and use it in GitHub Desktop.
Class to call external programs in Java and return the output String.
package util;
import java.io.BufferedReader;
import java.io.InputStreamReader;
/**
* Created by dan on 2/4/14.
*/
public class ProgramCaller {
private String program;
public ProgramCaller(String pname){
program = pname;
}
public ProgramCaller(){
program = "";
}
private String execute(String command){
StringBuffer output = new StringBuffer();
Process p;
try {
p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader reader =
new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
return output.toString();
}
public String runProgram(){
return execute(program);
}
public String runProgram(String pname){
return execute(pname);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment