ProcessBuilder无法读取执行文件

时间:2013-05-16 08:40:24

标签: java process processbuilder

c程序下面有两个参数a,b如果匹配来自用户输入,则打印值。我尝试在Java ProcessBuilder中运行c执行文件,但它不读取执行文件。

Java代码

import java.io.*;
import java.lang.Runtime;
import java.lang.*;
import java.io.File;
import java.lang.ProcessBuilder;
public class arg
{
 public static void main(String[] args)
 {
  try
  {
   ProcessBuilder pb = new ProcessBuilder("path","-args[1]", "-args[2]");
   pb.redirectErrorStream(true); 
   Process p = pb.start();
   String s;
   BufferedReader stdInput = new BufferedReader(new 
                                           InputStreamReader(p.getInputStream()));
   BufferedReader stdError = new BufferedReader(new 
                                           InputStreamReader(p.getErrorStream()));
   OutputStream stdOutput =   p.getOutputStream();                      
   stdOutput.close();
   while ((s = stdInput.readLine()) != null)
   { System.out.println(s);    }    
     System.out.println("Done.");
     stdInput.close();              
  }//try
  catch (IOException ex) { ex.printStackTrace();    }
    } //void
  } //main

c code

   #include <stdio.h>
   #include <sys/timeb.h>
   #include <string.h>
   main(int argc, char **argv)
   {
   setbuf(stdout, NULL);
   int i=1,j,n;
   char a,b;
   for (i=0; i<argc; i++)   
   { printf("%s\n", argv[i]); }

     if(!strcmp(argv[1],"a"))
     {
       if(!strcmp(argv[2], "b"))
       {    
       for( j = 0; j<= 4; j++ ) 
        { printf("Iteration[%d] %d\n",j, j); }
       }
       return 0 ;
    }
   } //main

2 个答案:

答案 0 :(得分:2)

我不清楚你要做什么,但是如果你想从java命令行传递ProcessBuilder参数,那么你需要做

ProcessBuilder pb = new ProcessBuilder("path", args[0], args[1]); // Note, index starts with 0

您这样做的方法是将实际字符串"arg[1]""arg[2]"发送到您的命令。

答案 1 :(得分:0)

你可能想写:

if (args.length >= 2)
    ProcessBuilder pb = new ProcessBuilder("path","-" + args[0], "-" + args[1]");

Java参数的索引是从0开始,而不是从1开始,第一个参数中没有程序名,就像在C中一样。