Link to home
Start Free TrialLog in
Avatar of avi_india
avi_india

asked on

Difference in executing a program from command line and from a Java program (i.e. using Runtime)

Hi All,

What is the difference between executing a program from command line and from a Java program (i.e. using Runtime).

e.g. lets say my program is myprog. If I give following in dos prompt, it works

myprog >>  select__history.out -echo -noprompt  -u user -p passwd < myfile


But, if I give the same to Java using following code :

---------------------------------------------------------------------------------------------------------
      String strCommand = "myprog >>  select__history.out -echo -noprompt  -u user -p passwd < myfile";
            
      try {
           String line;
           Process p = Runtime.getRuntime().exec(strCommand );
           BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
           while ((line = input.readLine()) != null) {
             System.out.println(line);
           }
           input.close();
      }
      catch (Exception err) {
           err.printStackTrace();
      }
            
---------------------------------------------------------------------------------------------------------

I get the following error :

unrecognized argument: ">>"

How can I execute this using java?


Thanks
Ajay
ASKER CERTIFIED SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of sciuriware
sciuriware

The <, > and >> arguments must be processed by a shell.
So your commandline on the dosprompt is processed by cmd.exe or command.exe,
depending on the Windows version.

All you have to do is put that program before all other characters:


cmd.exe MyProgram >> ...........

;JOOP!
You must pass the values correctly.
See here:
http://www.javaalmanac.com/egs/java.lang/Exec.html

Bye, Giant.
Avatar of avi_india

ASKER

Have gone thru these links.. Now I can execute these inputs and output for a program separately. I am not able to combine as required.

Can somebody please help me with that..

i.e. execute a program taking input from infile and sending output to outfile (or some variable - important is to capture the output). Program will also have some command line options.

SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hi Giant,

this helps.. but still it does not deal with input to the program which I achieve using "<" on the command line.
use Process.getOutputStream()

(from JavaDoc:

getOutputStream

public abstract OutputStream getOutputStream()

Gets the output stream of the subprocess.  Output to the stream is piped into the standard input stream of the process represented by this Process object.

Implementation note: It is a good idea for the output stream to be buffered.
)

So, get this OutputStream, open the file, and write each line of the file (myfile) to be redirected into the program (with "<") to this OutputStream (as recommended, use buffering, so probably better to use java.io.BufferedReader for the input, and java.io.PrintWriter for the output... assuming the file is ASCII, otherwise use java.io.BufferedWriter to write...

example:
// exception handling missing...
BufferedReader in = new BufferedReader( FileReader( "myfile" ) );

// assuming the Process returned by Runtime.exec() is "myProcess"
PrintWriter out = new PrintWriter( myProcess.getOutputStream() );

String line = in.readLine();
while( line != null ) {
    out.println( line );
    line = in.readLine();
}

// getting here means input is complete (should also handle exceptions carefully...)
out.close();
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
You should always put I/O redirections at the end of a commandline as those should NOT be passed
to the program. That would imply breaking the command line.
Exception on this in the merge redirection in the UNIX shells:   command >output 2>&1

So, retry with the < and >> at the end.
;JOOP!
>...still it does not deal with input to the program which I achieve using "<" on the command line.

In the link I post before:
http://www.javaalmanac.com/egs/java.lang/Exec.html
You can find this example:
>...it is necessary to use the overload that requires the command and its arguments to be supplied in an array:
    try {
        // Execute a command with an argument that contains a space
        String[] commands = new String[]{"grep", "hello world", "/tmp/f.txt"};
        commands = new String[]{"grep", "hello world", "c:\\Documents and Settings\\f.txt"};
        Process child = Runtime.getRuntime().exec(commands);
    } catch (IOException e) {
    }

Use this example with the parameters you want to use.
Bye, Giant.
Hi CEHJ/JOOP

Both does not work!!!.. :(

I have reached a point where I can execute one line using following code..


----------------------------------------------

public class DataFields {
      public static void main(String argv[])
      {
            String command = "sqlplus -dsn sql -u user -p passwd"; // assume that this is correct

            try {
                  String line;
            
                  Process child = Runtime.getRuntime().exec(command);
                  BufferedReader input =
                               new BufferedReader(new InputStreamReader(child.getInputStream()));
                           
                  
                 //   Get output stream to write from it
                  OutputStream out = child.getOutputStream();
                  
                  out.write("select * from tname;".getBytes());
                  // as soon as I add another out.write statement here - I start getting error
                  out.close();
                  
                  while ((line = input.readLine()) != null) {
                         System.out.println(line);
                  }
                  
                  input.close();
            }
            catch (Exception err) {
                 err.printStackTrace();
            }      
      }
}

---------------------------------------------------------------------
Use a PrintWriter for sending input:

PrintWriter out = new PrintWiter(child.getOutputStream());
out.println("select * from tname;");
Here's a couple of examples of reading output from Process that can be easily modified to suit your needs:

http://www.objects.com.au/java/examples/util/ConsoleExec.do
http://www.objects.com.au/java/examples/util/SwingExec.do
The redirect in *could* be a problem. I know it works with redirect out, so try object's suggestion
use the getOutputStream() as I suggested earlier... The reason I suggested the PrintWriter is that its easier to direct line seperated text...
>>use the getOutputStream() as I suggested earlier

Sorry, cjclifford, i forgot you'd mentioned that earlier
no problems :-)
I missed yours and objects comments - really should refresh before adding comments more often :-)

Nothing is actually working. I am able to execute only one statement. After that I have to re-execute, attach out & input streams again and then do the work. Can somebody please help me with execjuting statements again & again just as I do if I execute the program from command line.

-Ajay
To do that contiuously you need to execute a shell and put your statements (=commands) on the
standard output to this shell, another thread must read the output back.
Note that this demand differs from your original question!
;JOOP!
I understand that this is a bit different.. But how do i know that you can't put the above given solutions to work as in this way!!!!!!

SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
8-)
8-)
thanks.
:)