Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package sample;
- import java.io.BufferedReader;
- import java.io.File;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.util.Map;
- /**
- * Simple usage example for class java.lang.ProcessBuilder under Windows (XP, Vista, ...)
- */
- public class ProcessBuilderTest {
- /**
- * @param args no arguments needed
- */
- public static void main(String[] args) {
- ProcessBuilder pb = new ProcessBuilder();
- pb.redirectErrorStream(true);
- pb.directory(new File("C:/"));
- pb.command("cmd", "/c", "dir");
- //Map<String, String> env = pb.environment();
- //env.put("PB_SAMPLE_VAR", "Hello World!");
- //pb.command("cmd", "/c", "echo", "%PB_SAMPLE_VAR%");
- Process p;
- try {
- p = pb.start();
- }
- catch (Exception e) {
- e.printStackTrace();
- System.exit(1);
- return;
- }
- System.out.println("stdout/stderr of command: " + pb.command());
- System.out.println("-------------------------");
- InputStreamReader isr = null;
- BufferedReader br = null;
- try {
- isr = new InputStreamReader(p.getInputStream());
- br = new BufferedReader(isr);
- String line;
- for (;;) {
- try {
- line = br.readLine();
- if (line == null) {
- break;
- }
- System.out.println(line);
- }
- catch (IOException e) {
- e.printStackTrace();
- break;
- }
- }
- }
- finally {
- if (br != null) {
- try { br.close(); } catch (Exception ex) { /* */ }
- }
- }
- int exitcode = -1;
- try {
- exitcode = p.waitFor();
- } catch (InterruptedException e) {
- e.printStackTrace();
- exitcode = -42;
- }
- System.out.println("-------");
- System.out.println("exitcode: " + exitcode);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment