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

来源:互联网 发布:淘宝网卖家登陆 编辑:程序博客网 时间:2024/06/10 07:09
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());
        }
    }

}
0 0
原创粉丝点击