作者darkk6 (CJV)
看板java
标题Re: [问题] 在Linux底下执行外部程式?
时间Sat Oct 30 16:06:12 2010
※ 引述《CSLabor (电脑工人)》之铭言:
: 我在Linux底下已经写了一个简单的helloworld执行档
: 档名叫helloworld
: 用途是print出一串helloworld
: 现在我要用java程式呼叫这个执行档
: 这个Java程式档名叫做helloworld.java
: helloworld.java内容如下
: import java.io.*;
: public class helloworld{
: public static void main(String[] args){
: try{
: String[] command={"/bin/sh","./helloworld"};
: Runtime.getRuntime().exec(command);
: }
: catch(IOException e){
: e.printStackTrace();
: }
: }
: }
: 我的程式编译执行後没有反应
: 可以请有经验的大大可以帮我看一下吗?
: 在这边先谢谢有经验的前辈
如果你的 helloworld 是 .sh 档的话,那麽这样写应该是没问题
如果是单一执行档,是否还需要透过 sh 也是一个问题...
因为在 windows 底下有 .exe 也是无法执行的情况,需要透过 cmd
cmd /C ???.exe 这样
如果要取得那个程式输出的资料:
Process p=Runtime.getRuntime().exec(command);
然後 p.getInputStream() 取得 InputStream (个人习惯是喂给 Scanner 吃)
然後再印出来,如;
Process p=Runtime.getRuntime().exec(command);
Scanner ipt=new Scanner(p.getInputStream());
while(ipt.hasNextLine())
System.out.println(ipt.nextLine());
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 122.123.84.166
1F:推 CSLabor:谢谢两位前辈的帮忙 10/30 18:27