Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Thursday, January 27, 2011

Running Cygwin command from java

Lets take simple ls command to be run inside java code
Following are the steps

File workDir = new File("C:/cygwin/bin");
String cmd = "bash --login -i -c \" ls \"";
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(workDir+"/"+cmd, null, workDir);
int i = pr.waitFor();


if (i == 0){
BufferedReader input1 = new BufferedReader(new InputStreamReader(pr.getInputStream()));

String line=null;
while((line=input1.readLine()) != null) {
System.out.println(line);
}
}else{
BufferedReader stdErr = new BufferedReader(new InputStreamReader(pr.getErrorStream()));
// read the output from the command
String s = null;
while ((s = stdErr.readLine()) != null) {
System.out.println(s);
}
}