Search code examples
javaprocessprocessbuilder

ProcessBuilder not read execute file


Below c program has two arguments a,b if it is match from user input,it print the values. I try to run c execute file in Java ProcessBuilder, but it does not read execute file.

Java code

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

Solution

  • It's not clear to me what you're trying to do, but if you want to pass the ProcessBuilder the parameters from the java command line, then you need to do

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

    The way you do it, you're sending the actual strings "arg[1]" and "arg[2]" to your command.