【博客搬家】java中exec函数使用说明

http://key.blog.ccidnet.com/blog-htm-do-showone-uid-22191-type-blog-itemid-60734.html


Process process = Runtime.getRuntime().exec ("ls");
说明:
1.     exec的必须是可执行的程序,如果是命令行的命令则还需另外处理
2.     在windows中process = runtime.exec(new String[] { "cmd.exe","/C", "dir"});
3.     在linux中process = runtime.exec(new String[] { "/bin/sh","-c", "echo $PATH"});

Windows中exec应用示例:
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

public class compiler {

    public static void main(String[] args) {

        Runtime runtime = Runtime.getRuntime();
        Process process = null;
        String line = null;
        InputStream is = null;
        InputStream es = null;
        InputStreamReader isr = null;
        InputStreamReader esr = null;
        BufferedReader ibr = null;
        BufferedReader ebr = null;
        String[] env = null;
        File file = new File("D://3.1.2//eclipse");

        try {
              process = runtime.exec(new String[] { "cmd.exe", "/C",
                      "eclipse -nl english" }, null, file);
        } catch (IOException e) {
              System.out.println(e);
        }
        // 取得子进程的输出流
        is = process.getInputStream();
        isr = new InputStreamReader(is);
        ibr = new BufferedReader(isr);
        // 取得子进程的错误流
        es = process.getErrorStream();
        esr = new InputStreamReader(es);
        ebr = new BufferedReader(esr);
        /***********************************************************************
          * 如果子进程还要求有输入,则增加这样的方法
          * OutputStream outputToChild =process.getOutputStream(); try { outputToChild.write(("your_command" +
          * "/n").getBytes());
          * outputToChild.flush(); }
          * catch (IOException e) {
          * System.out.println(e); }
          */
        try {
              while ((line = ibr.readLine()) != null) {
                  System.out.println(line);
              }
        } catch (IOException e) {
              System.out.println(e);
              e.printStackTrace();
        }

        try {
              while ((line = ebr.readLine()) != null) {
                  System.out.println(line);
              }
        } catch (IOException e) {
              System.out.println(e);
              e.printStackTrace();
        }

    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值