首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用一些参数从Java中调用.exe文件

如何使用一些参数从Java中调用.exe文件
EN

Stack Overflow用户
提问于 2015-11-13 05:15:09
回答 2查看 144关注 0票数 3

我需要调用cowsay.exe (这个程序使用符号来绘制动物),并执行命令: cowsay "hello“。如何将"hello“作为参数传递?

代码语言:javascript
复制
public class cowsay {
    public static void main(String[] args) throws IOException {
        Process process = new ProcessBuilder("D:\\cowsay.exe","cowsay Hello").start();
        InputStream is = process.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String line;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
    }
EN

回答 2

Stack Overflow用户

发布于 2015-11-13 05:24:19

您可以使用java.lang.Runtime类:

代码语言:javascript
复制
public class cowsay {
    public static void main(String[] args) throws IOException {
        Process process = 
                Runtime.getRuntime().exec("cowsay hello");
        InputStream is = process.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String line;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
    }
}
票数 4
EN

Stack Overflow用户

发布于 2015-11-13 17:33:29

正如Fungucide指出的那样,您可以使用RunTime类。但是,我建议您使用将参数作为数组接受的方法。示例代码:

代码语言:javascript
复制
public static void main(String[] args)  {
  Try{
     String[] command={"D:\\cowsay.exe","cowsay","Hello"};
            Runtime.getRuntime().exec(command);
    }catch(Exception e){System.out.println(e.getMessage());}
}

这是如果您想要将"cowsay“作为参数的话。如果你想要“d=only”作为参数,那么你可以这样做:

代码语言:javascript
复制
public static void main(String[] args)  {
  Try{
     String[] command={"D:\\cowsay.exe","Hello"};
            Runtime.getRuntime().exec(command);
    }catch(Exception e){System.out.println(e.getMessage());}
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33681500

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档