`
ericwzc
  • 浏览: 12043 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

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());
	}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics