java 调用系统进程

	public static void main(String[] args) throws IOException,
			InterruptedException {
		ProcessBuilder pb = new ProcessBuilder("CMD /C dir".split(" "));
		pb.redirectErrorStream(true);//so no need to start another thread to purge error stream
		final Process p = pb.start();
		final StringBuffer sb = new StringBuffer();
		Thread t = new Thread(new Runnable() {
			@Override
			public void run() {
				BufferedReader br = new BufferedReader(new InputStreamReader(
						p.getInputStream()));
				try {
					try {
						String s = null;
						while ((s = br.readLine()) != null) {
							sb.append(s+"\n");
						}
					} finally {
						br.close();
					}
				} catch (Exception ex) {
					throw new RuntimeException(ex);
				}
			}
		});
		t.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
			@Override
			public void uncaughtException(Thread t, Throwable e) {
				System.out.println(e);
			}
		});
		t.start();
		p.waitFor();//blocks
		System.out.println("exit val: " + p.exitValue());
		System.out.println(sb.toString());
	}

你可能感兴趣的:(java)