Skip to content

Instantly share code, notes, and snippets.

@goyuninfo
Last active January 26, 2016 21:26
Show Gist options
  • Save goyuninfo/8243430 to your computer and use it in GitHub Desktop.
Save goyuninfo/8243430 to your computer and use it in GitHub Desktop.
package ca.i88.example;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
*
* @author i88.ca
*/
public class CallShellCommandExample {
public static void main(String[] args) throws IOException, InterruptedException {
Process p;
//old way
p = Runtime.getRuntime().exec("date");
p.waitFor();
BufferedReader reader
= new BufferedReader(new InputStreamReader(
p.getInputStream()));
String line;
while (true) {
line = reader.readLine();
if (line == null) {
break;
}
System.out.println(line);
}
//new way
ProcessBuilder pb = new ProcessBuilder("hostname");
p = pb.start();
p.waitFor();
reader = new BufferedReader(new InputStreamReader(
p.getInputStream()));
while (true) {
line = reader.readLine();
if (line == null) {
break;
}
System.out.println(line);
}
//with parameters
ProcessBuilder pb2 = new ProcessBuilder("dig","it.i88.ca","@8.8.8.8");
p = pb2.start();
p.waitFor();
reader = new BufferedReader(new InputStreamReader(
p.getInputStream()));
while (true) {
line = reader.readLine();
if (line == null) {
break;
}
System.out.println(line);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment