Solved

Runtime.exec()

Posted on 2000-04-07
11
1,732 Views
Last Modified: 2008-02-26
UpdateVC4.bat is a batch file
that runs the ftp script Ftp4.txt

contents of UpdateVC4.bat:
echo Update price message being sent . Please wait ......................"

start ftp -s:Ftp4.txt


pause

exit


Contents of Ftp.txt:

//actual address omitted
open   000.000.000.000
anonymous  anonymous
bin

cd   d:\iFtpSvc\ussjccf5\users\outbound\

put  d:\iFtpSvc\ussjccf5\users\outbound\APIVALDTQ.txt    c:\iFtpSvc\ussjccf5\users\outbound\APIVALDTQ.txt

quit


The batch file works independantly when run from a command prompt and when the java application is run on my machine but in the test environment it doesn't

Java code that runs the script:

import java.io.*;


public class Ftp extends Thread {

  public Ftp() {
  // System.out.println("a new ftp created");
  }

  public void run()
  {
       Process p = null;
   //  String[] command = {"uploadVC4.bat"};

 
// I have also tried the following but the batch file is in the same directory
//as the application so the above  code should work

 /*  String[] command =  {"d:\\Rhythm\\Customer_Commitment_Suite\\InternetServer\\lib\\uploadVC4.bat"};  

 */
       System.out.println(" ftp started");
      //Runtime rt = Runtime.getRuntime();
   try {

        p = Runtime.getRuntime().exec(command);

        try{
        p.waitFor();
        } catch ( InterruptedException e ) {


        }
   } catch ( IOException e) {

  }


   p.destroy();
   p = null;
  }


}

exit
0
Comment
Question by:admiral
  • 6
  • 2
  • 2
  • +1
11 Comments
 
LVL 19

Expert Comment

by:Jim Cakalic
ID: 2696140
The problem is likely to be that the environment of the test machine doesn't match the environment of your machine, particularly with respect to the definition of the PATH variable.

Runtime.exec(), at least on win32 systems, uses a version of CreateProcess that searches the directories defined in the PATH variable for the 'executable' file unless the filename defines a full path or a path relative to the current working directory. CreateProcess also looks in the current working directory.

Since you are probably running the interpreter having set your working directory to the location of the class and batch files, it is able to find both and your program executes. When you move the application to the production environment, this is no longer the case.

Try looking at the exception stack trace you get in the test environment. In the code you posted you are ignoring the exception so you should add e.printStackTrace() to the body of the catch block. I'm betting it will look something like this:

java.io.IOException: CreateProcess: junk.bat error=2
        at java.lang.Win32Process.create(Native Method)
        at java.lang.Win32Process.<init>(Unknown Source)
        at java.lang.Runtime.execInternal(Native Method)
        at java.lang.Runtime.exec(Unknown Source)
        at java.lang.Runtime.exec(Unknown Source)
        at java.lang.Runtime.exec(Unknown Source)
        at java.lang.Runtime.exec(Unknown Source)
        at RuntimeExec.main(RuntimeExec.java:10)

The "CreateProcess: junk.bat error=2" is telling you that CreateProcess cannot find the specified file. Error=2 is familiar to old C hacks like me because it is the well known errno value for 'file not found'.

If this is the case, you have several possibilites, right? 1) Hardcode the path to the batch file (yuck). 2) Change the test (and subsequently production) environment to include the necessary paths. 3) Use ClassLoader.getSystemResource(String name) to find a named resource from the search path used to load classes. I'm not sure this last would work but, if so, it would look something like:

    ClassLoader cl = ClassLoader.getSystemClassLoader();
    URL url = cl.getSystemResource("UpdateVC4.bat");

Best regards,
Jim Cakalic
0
 

Author Comment

by:admiral
ID: 2696603
The error code produced by the
printStackTrace call was:


java.io.IOException: CreateProcess: junk.bat error=3  

What does 3 mean ?
 
After setting the path the error does not appear but the program does not execute.


     
0
 

Author Comment

by:admiral
ID: 2696721
Also when the absolute path is set in the exec call the program still does not run
0
 

Expert Comment

by:Ash_
ID: 2698078
Hi admiral,

When using Runtime.exec(), you can execute only executable files eg. EXE,COM,etc in Windows. You cannot "execute" a batch file . It is actually interpreted by the Command Line Interpreter "command.com" for Win95 & "cmd.exe" for WinNT. So try this

String[] command  =  {"command.com /c uploadVC4.bat"};

BTW if the contents of the batch file are the same then try

String[] command  =  {"start.exe","ftp","-s:Ftp4.txt"};
0
 
LVL 19

Accepted Solution

by:
Jim Cakalic earned 200 total points
ID: 2699032
Hmm. Had this same discussion with different experts on another thread. I'm running jdk1.3rc2 on NT4/SP5. The following code sample shows how I can successfully execute batch files without the benefit of running a separate command shell:

---------- RuntimeExec.java ----------
import java.io.*;

public class RuntimeExec {
    public static void main(String[] args) {
        if (args.length == 0) {
            System.exit(0);
        }
        Process p;
        try {
            p = Runtime.getRuntime().exec(args[0]);
            System.out.println("Found " + args[0]);
            InputStream is = p.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader reader = new BufferedReader(isr);
            String line = null;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            int status = p.waitFor();
            System.out.println("Process exited (" + status + ")");
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.exit(0);
    }
}

---------- hello.bat ----------
@echo off
echo hello, world

Running 'java RuntimeExec hello.bat' from the MS-DOS Command Prompt produces the following output:

Found hello.bat
hello, world
Process exited (0)

Best regards,
Jim Cakalic

0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 19

Expert Comment

by:Jim Cakalic
ID: 2699071
Sorry, I forgot to say that win32 error code 3 is path not found -- the system cannot find the path specified.

Jim Cakalic
0
 

Expert Comment

by:xjeffk
ID: 2793081
jim, can i call the above code from another java file ( removing the main & slapping the rest of your code into a method ) with same results?
0
 
LVL 19

Expert Comment

by:Jim Cakalic
ID: 2793617
Sure. With the exception of the reference to args, this section of code should be usable anywhere:

        Process p;
        try {
            p = Runtime.getRuntime().exec(args[0]);
            System.out.println("Found " + args[0]);
            InputStream is = p.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader reader = new BufferedReader(isr);
            String line = null;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            int status = p.waitFor();
            System.out.println("Process exited (" + status + ")");
        } catch (Exception e) {
            e.printStackTrace();
        }

Best regards,
Jim Cakalic
0
 
LVL 19

Expert Comment

by:Jim Cakalic
ID: 2793627
Um -- well -- you probably don't want the System.out.printlns either :-) And you'll do something useful with the data piped back from the external process.
0
 

Expert Comment

by:xjeffk
ID: 2793808
ok - yeah.. i did try this..  no deal..

problem i'm trying to beat is: from a servlet, call runtime.exec("net use lpt1: \\\\servername\\printername ")

i have this working in a standalone program, but it doesn't work from a servelt..  i'm playing with your file to try to somehow spit out my dos command..

any ideas??
0
 
LVL 19

Expert Comment

by:Jim Cakalic
ID: 2795389
Could it be a PATH problem? Have you tried specifying the full path to the net.exe file in the exec call? On my system (NT4) that is C:\Winnt\system32\net.exe. Are there any exceptions thrown? I'm not that familiar with servlet programming so I don't know where the stack trace for these would appear. I also don't know what possible restrictions there might be on servlets. Since they run on the server side, I'm guessing they have fairly unrestricted access to the system so security profile shouldn't be an issue ...
0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
scoresSpecial  challenge 13 42
sumDigits  challenge 7 62
Eclipse Neon and jdk 1.8.0 11 72
base64 decode encode 12 98
An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

759 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now