2009年3月23日

ProcessBuilder getInputStream

exec : Java Glossary

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

public class Main {

public static void main(String[] args) throws IOException {
String[] cmd = { "cmd", "/c", "dir" };
File currentDirectory = new File("/");
int exitValue = -1;
String path = null;

final StringBuilder sb = new StringBuilder();
ProcessBuilder pb = new ProcessBuilder(cmd);
pb = pb.redirectErrorStream(true);
path = pb.environment().get("Path");
pb.directory(currentDirectory);
Process p = pb.start();
final BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
try {

Thread t = new Thread(new Runnable() {
public void run() {
String line;
try {
while ((line = br.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (Exception e) {
e.printStackTrace();
}

}
});
t.start();
try {
p.waitFor();
t.join();
exitValue = p.exitValue();
}

catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
} finally {
br.close();
p.getOutputStream().close();
p.getErrorStream().close();
}

System.out.println("PATH: " + path);
System.out.println("Run Command: " + Arrays.toString(cmd));
System.out.println("Current Directory: " + currentDirectory);
System.out.println("exitValue: " + exitValue);
System.out.println("stdout: ");
System.out.println(sb);

System.exit(0);
}

}

/*
PATH: D:/java/jdk1.6.0_13/bin/...
Run Command: [cmd, /c, dir]
Current Directory: \
exitValue: 0
stdout:
磁碟區 C 中的磁碟沒有標籤。
磁碟區序號: 0870-0C1B

C:\ 的目錄

2009/03/09 下午 01:45 0 AUTOEXEC.BAT
2009/03/09 下午 01:45 0 CONFIG.SYS
2009/03/20 上午 09:07 <DIR> Documents and Settings
2009/03/23 下午 04:44 <DIR> Program Files
...
*/

沒有留言:

網誌存檔