现在的位置: 首页 > 综合 > 正文

通过JAVA在命令行(如控制台)运行Shell指令

2013年04月15日 ⁄ 综合 ⁄ 共 858字 ⁄ 字号 评论关闭
package com.things.boring.runtime;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class RuntimeTest {

    /**
     * Run a command in the command line just like the console.
     */
    public static void main(String[] args) throws IOException {

        Process process = null;
        Runtime rt = Runtime.getRuntime();
        try {
            process = rt.exec("ls -la");
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            process.waitFor();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        InputStream is = process.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String b;
        while((b=br.readLine())!=null){
            System.out.println(b);
            System.out.println(br.readLine());
        }
    }

}

抱歉!评论已关闭.