URGENT:- Running a batch file from java program

Author: pkanury
I am trying to execute a batch file from my java program using RunTime and Process . It can execute any dos command except for a batch file. Can anyone throw
some light ?? My code looks like this .....
cmd = "command.com /c X:\\grits\\scripts\\test.bat"; Runtime rt = Runtime.getRuntime(); Process p = rt.exec(cmd);
The weird part is that p.waitFor() returns a status of 0 implying that the cmd has been executed successfully. But that is not the case. And my batch file is as simple as - type "ADADA" > junk.txt
Any help would be appreciated.

I think it should work when you use a String[] array
instead of a single String:
String[] cmd = { "command.com", "/C", "D:\\batch\\do.bat" };
Note: If the batchfile creates any output (i.e. files),
they will be stored in the directory of the application
which calls the batch file, not in d:\batch\...

Similar Messages

  • Calling batch file from java Program

    I have made the java program in which i have called the batch file.But the problem is this that when i call batch file locally it executes normally but when i try to execute batcvh file from remote machine it doesn't runrather it gives Runtime IO execption.Error123.Can anyone provide me the solution for this?

    Not without a lot more information. Like for example how you are trying to execute this remote batch file, the code you are using to do that, what kind of server you have no the remote machine to let you remotely execute code, and so on.

  • Run a batch file from java

    Hi,
    is there any chance to run a file , with the ending .bat. I was able to run run one with the ending .exe. Are there any limitations.
    Greetings
    tom

    what about running "cmd.exe /k script.bat"

  • Running batch files  from Java using exec method

    Hi,
    I want to run a batch file from my Java program like this:
    try {
    Process proc = Runtime.getRuntime().exec("C:\\Refresh.bat");
    catch (Exception e) {
    MessageBox.show(e.getMessage());
    Refresh.bat file contains two commands.
    First one unzips certain zip file.
    Second one refreshes a SQL Server database using osql utility.
    Problem is that when program is run it executes only the first command and hangs on the second one.
    Please help.
    TIA
    Ravinder

    From the FAQ:
    2. How do you launch an external program on a Microsoft Windows platform from a program developed on the Java [tm] programming language?
    The following will launch notepad in Microsoft Windows NT:
    Runtime.getRuntime().exec("cmd /c notepad.exe");
    To launch a program in Microsoft Windows 95/98 use:
    Runtime.getRuntime().exec("c:\\windows\\notepad.exe");
    The Runtime class allows interaction between a program and its environment. The first string command instructs the command line interpretor, cmd to open up the calculator application.
    The exec() methods do not use a shell; any arguments must have the full pathname to the shell as well as the command itself.
    For example, to run a shell on the UNIX� platform, type:
    Runtime rt = Runtime.getRuntime();
    Process p = rt.exec("/usr/bin/sh -c date");
    To run a batch file under Microsoft Windows 95/98:
    Process p = rt.exec("command.com /c c:\\mydir\\myfile.bat");
    To run a batch file under Microsoft Windows NT:
    Process p = rt.exec("cmd /c c:\\mydir\\myfile.bat");
    where 'cmd' and 'command.com' are the command-line interpreters for Microsoft Windows machines.
    The Runtime.exec() methods might not work effectively for some processes on certain platforms. Special care should be taken with native windowing, daemon, WIN16/DOS process or some shell scripts.
    regards,
    jarshe

  • Running a batch file in Java. Urgent!!

    I want to run a batch file present at a particular location in Java.Although I am running two codes suggested by many people, i am still not able to run the batch file. My codes run as below :-
    CODE 1
    Process P;
    Runtime rt = Runtime.getRuntime();
    P = rt.exec("C:\\test.bat");
    CODE 2
    Process P;
    Runtime rt = Runtime.getRuntime();
    P = rt.exec("C:\\WINNT\\System32\\cmd.exe C:\\test.bat");
    I have tried both these codes but without success. But I have observed that in the Task Manager, whenever i run the above codes in a servlet, a "CMD.EXE" is being created in the "Processes" Bar each time but the batch file neither opens up nor it runs.
    Please suggest me some method to run this batch file in Java.
    Or if u can suggest the reason behind the above observation and any corrections i can make to run the batch file. Thanks in advance.
    Ankit

    i want to get more than one command prompt while running the program
    am giving the problem
    import java.io.*;
    class CmdDemo
         CmdDemo(String ls) {
              try
              Process p;
              Runtime rt=Runtime.getRuntime();
              p=rt.exec(ls);
              catch(IOException ioe)
                   System.out.println(ioe);
         void showcmd(){
    new CmdDemo("cmd");
         public static void main(String args[])
              new CmdDemo("cmd");
              new CmdDemo("C:/WINDOWS/System32/cmd.exe");
              new CmdDemo("cmd");
              new CmdDemo("regedit");
              new CmdDemo("regedit");
              new CmdDemo("notepad");
              new CmdDemo("notepad");
              //CmdDemo cd=new CmdDemo("cmd");
              //cd.showcmd();
    here am getting two notepads ,two registry editors
    but only one command window
    i would be very greateful if u could help me
    plz reply to my id [email protected] too

  • Executing batch file from Java stored procedure hang

    Dears,
    I'm using the following code to execute batch file from Java Stored procedure, which is working fine from Java IDE JDeveloper 10.1.3.4.
    public static String runFile(String drive)
    String result = "";
    String content = "echo off\n" + "vol " + drive + ": | find /i \"Serial Number is\"";
    try {
    File directory = new File(drive + ":");
    File file = File.createTempFile("bb1", ".bat", directory);
    file.deleteOnExit();
    FileWriter fw = new java.io.FileWriter(file);
    fw.write(content);
    fw.close();
    // The next line is the command causing the problem
    Process p = Runtime.getRuntime().exec("cmd.exe /c " + file.getPath());
    BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line;
    while ((line = input.readLine()) != null)
    result += line;
    input.close();
    file.delete();
    result = result.substring( result.lastIndexOf( ' ' )).trim();
    } catch (Exception e) {
    e.printStackTrace();
    result = e.getClass().getName() + " : " + e.getMessage();
    return result;
    The above code is used in getting the volume of a drive on windows, something like "80EC-C230"
    I gave the SYSTEM schema the required privilege to execute the code.
    EXEC DBMS_JAVA.grant_permission('SYSTEM', 'java.io.FilePermission', '<<ALL FILES>>', 'read ,write, execute, delete');
    EXEC DBMS_JAVA.grant_permission('SYSTEM', 'SYS:java.lang.RuntimePermission', 'writeFileDescriptor', '');
    EXEC DBMS_JAVA.grant_permission('SYSTEM', 'SYS:java.lang.RuntimePermission', 'readFileDescriptor', '');
    GRANT JAVAUSERPRIV TO SYSTEM;
    I have used the following to load the class in Oracle 9ir2 DB:
    loadjava -u [system/******@orcl|mailto:system/******@orcl] -v -resolve C:\Server\src\net\dev\Util.java
    CREATE FUNCTION A1(drive IN VARCHAR2) RETURN VARCHAR2 AS LANGUAGE JAVA NAME 'net.dev.Util.a1(java.lang.String) return java.lang.String';
    variable serial1 varchar2(1000);
    call A1( 'C' ) into :serial1;
    The problem that it hangs when I execute the call to the function (I have indicated the line causing the problem in a comment in the code).
    I have seen similar problems on other forums, but no solution posted
    [http://oracle.ittoolbox.com/groups/technical-functional/oracle-jdeveloper-l/run-an-exe-file-using-oracle-database-trigger-1567662]
    I have posted this in JDeveloper forum ([t-853821]) but suggested to post for forum in DB.
    Can anyne help?

    Dear Peter,
    You are totally right, I got this as mistake copy paste. I'm just having a Java utility for running external files outside Oracle DB, this is the method runFile()
    I'm passing it the content of script and names of file to be created on the fly and executed then deleted, sorry for the mistake in creating caller function.
    The main point, how I claim that the line in code where creating external process is the problem. I have tried the code with commenting this line and it was working ok, I made this to make sure of the permission required that I need to give to the schema passing security permission problems.
    The function script is running perfect if I'm executing vbs script outside Oracle using something like "cscript //NoLogo aaa1.vbs", but when I use the command line the call just never returns to me "cmd.exe /c bb1.bat".
    where content of bb1.bat as follows:
    echo off
    vol C: | find /i "Serial Number is"
    The above batch file just get the serial number of hard drive assigned when windows formatted HD.
    Same code runs outside Oracle just fine, but inside Oracle doesn't return if I exectued the following:
    variable serial1 varchar2(1000);
    call A1( 'C' ) into :serial1;
    Never returns
    Thanks for tracing teh issue to that details ;) hope you coul help.

  • I need to call a batch file from java and pass arguments to that Batch file

    Hi,
    I need to call a batch file from java and pass arguments to that Batch file.
    For example say: The batch file(test.bat) contains this command: mkdir
    I need to pass the name of the directory to the batch file as an argument from My Java program.
    Runtime.getRuntime().exec("cmd /c start test.bat");
    How to pass argument to the .bat file from Java now ?
    regards,
    Krish
    Edited by: Krish4Java on Oct 17, 2007 2:47 PM

    Hi Turing,
    I am able to pass the argument directly but unable to pass as a String.
    For example:
    Runtime.getRuntime().exec("cmd /c start test.bat sample ");
    When I pass it as a value sample, I am able to receive this value sample in the batch file. Do you know how to pass a String ?
    String s1="sample";
    Runtime.getRuntime().exec("cmd /c start test.bat s1 ");
    s1 gets passed here instead of value sample to the batch file.
    Pls let me know if you have a solution.
    Thanks,
    Krish

  • Run a batch file from demantra workflow

    I am trying to run a batch file from demantra's workflow by creating an executable step.
    I am getting the following error.
    Error description ’’Invalid command line:’’"D:\Oracle Demantra Spectrum\Collaborator\demantra\sop\populate_staging.bat"
    I am giving the following value in command line of executable step.
    "#application_root#\sop\populate_staging.bat"
    The batch file exists in the appropriate folder.
    Following code is in the batch file.
    sqlldr userid=msdem/msdem@demsbx control=load_item_hier.ctl
    Please help me.
    Thanks

    This should work for you-
    Create a batch file on your current server (ODI) and write in the path to the other batch file on the other server.
    //Server2completename/D$/Path/yourbatchfile.bat
    From ODI call your batch file that you created on the same machine.. which will inturn call the other batch file on a different machine to execute batch client.
    Also can you paste the errors that you may be getting.. need to check if you are getting any specific issue related to this.
    Thanks
    Denzz

  • How to Call .XDO file From Java Program

    Hi,
    I have developed a report in using BI Publisher version 10.1.3.
    I created the report and it only created XDO files. If I want to call XDO file from Java program how I can do that.
    What are the APIs available to do that.
    Thanks
    -Ashutosh

    Hi,
    the JavaAPI didn't work with the xdo-Files. But you can create a proxy stub for the Web Service API of BI Publisher which uses the xdo's in the repository.
    regards
    Rainer

  • Execute a .cmd file from Java program on tomcat which is running as service

    I have a .cmd/,.bat file which has to be executed depending on the parameters I pass through JSP page hosted on a tomcat instance.
    Tomcat is running as a windows service.
    I need my .cmd file to be opened in a cmd or DOS box so that user can interact with the dos window, which is mandatory.
    When I run the program from eclipse it works well but on the tomcat , the server side the output of the command is written to my log file and it gives no chance for users to monitor and interact with the command.
    Should I do something with log4j settings or is due to tomcat running as service?
    Please help.
    thanks

    thanks for the responses.
    But the design is like that.Then it needs to be fixed.
    I think this is why there's a shortage of people to write computer applications, they are all wasting their time struggling to implement bad designs.
    its a scheduler to be run on tomcat where we interact
    with the running batch files and can't be changed.A scheduler in Tomcat? Why run a scheduler in an application server?
    any help is appreciated.
    I tried to execute the batch file from servlet it
    runs , but i see the cmd.exe in windows task manager
    and need a dos box open.
    Any ideas?If you need a DOS box open then you need a signed-on user. So here's my patch:
    1. Write an application that listens for messages from this Tomcat scheduler, and when it receives those messages it does something in a DOS box.
    2. Have somebody sign on to the server and run that application.
    3. Change the Tomcat scheduler to send messages to that application instead of trying to actually run it.
    It's up to you what kind of messages you should send. There are plenty of choices.

  • Error running batch files from java source file???

    Dear Friends,
    hi,
    this is with response to a doubt i had earlier ,
    i want to run batch files from the java source file ,i tried using this code (here batrun is the batch file name that contains commands to run other java files)
    try
    String [] command = {"c:\\vishal\\finalmain\\batrun"};
    Runtime.getRuntime().exec(command);
    catch(Exception e)
    but i got the following error.
    java.io.IOException: CreateProcess: gnagarrun error= 2
    plz. help me, i tried all combination w/o success,
    in anticipation(if possible give the code after testing)
    Vishal.

    hello there,
    i solved the prob. by using
    cmd /c start filename ,but i need to pass parameters ie
    cmd /c start java "c:/vishal/runfile a b" where a and b are the parameters. but it is not accepting this in Runtime.getRuntime.exec(),
    any solutions ?????????
    regards,
    Vishal

  • How to run a batch file from within an Oracle 9i Form?

    Hi, I would like to execute a batch file from within an oracle form - I'm assuming there's some PLSQL command I can use? I am not allowed to use any third party libraries, and I'm hoping I can get away without having to progam any C or Java to do it. I don't want to run my java program from my form, but my lecturer is insisting on it.
    Can anyone help?
    Thanx
    Adam

    Can u give me an example
    I need to run a batch files that does a series of step doing dir ( in 3 different folders)
    after each one it shows on screen with a pause & user press enter
    can this work out ?

  • Run remote batch file from Web Application Server

    Hello,
    I've developyed a Java program and deployed it on WAS v7.1.
    My java program tries to run a remote batch file which is located on remote Windows file system (and not on the WAS file system itself).
    The batch file was launched on the remote server (I saw it on the Task Manager of the remote server), but the remote batch file actually wasn't run (it was stuck).
    In order to run the remote batch file from my java program that is deployed on the WAS I've created a batch file on the WAS file system which its contnet is:
    cd c:\jobs
    psexec.exe 
    iltlvt40 -u SAPServiceCE1 -p a2i2000! c:\automation\DiskSpace\runDiskSpace.bat
    The jobs folder contains the psexec.exe file (you can find more details about the psexec on this link: http://technet.microsoft.com/en-us/sysinternals/bb897553.aspx).
    iltlvt40 is the remote server.
    SAPServiceCE1/a2i2000! is a user/password on the remote server which has a full permissions.
    My java program calls this batch file using the Runtime.exec() java method in order to run the remote batch file.
    Please guide me how to solve this problem?
    Best regards,
    Ahmad

    Hi,
    To which batch file you have meant to add some commands: for the local one or remote?
    I've added to the local one some different commands and it's works.
    I think there is a permission problem when we are trying to go out of the WAS file system.
    Best regards,
    Ahmad

  • How to pass arguments to a batch file from java code

    Hi
    I have a batch file (marcxml.bat) which has the following excerpt :
    @echo off
    if x==%1x goto howto
    java -cp C:\Downloads\Marcxml\marc4j.jar; C:\Downloads\Marcxml\marcxml.jar; %1 %2 %3
    goto end
    I'm calling this batch file from a java code with the following line of code:
    Process p = Runtime.getRuntime().exec("cmd /c start C:/Downloads/Marcxml/marcxml.bat");
    so ,that invokes the batch file.Till that point its ok.
    since the batch file accpets arguments(%1 %2 %3) how do i pass those arguments to the batch file from my code ...???
    %1 is a classname : for ex: gov.loc.marcxml.MARC21slim2MARC
    %2 is the name of the input file for ex : C:/Downloads/Marcxml/source.xml
    %3 is the name of the output file for ex: C:/Downloads/Marcxml/target.mrc
    could someone help me...
    if i include these parameters too along with the above line of code i.e
    Process p = Runtime.getRuntime().exec("cmd /c start C:/Downloads/Marcxml/marcxml.bat gov.loc.marcxml.MARC21slim2MARC C:\\Downloads\\Marcxml\\source.xml C:\\Downloads\\Marcxml\\target.mrc") ;
    I get the following error :
    Exception in thread main java.lang.Noclassdef foundError: c:Downloads\marcxml\source/xml
    could some one tell me if i'm doing the right way in passing the arguments to the batch file if not what is the right way??
    Message was edited by:
    justunme1

    1 - create a java class (Executer.java) for example:
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    public class Executer {
         public static void main(String[] args) {
              try {
                   for (int i = 0; i < args.length; i++) {
                        System.out.println(args);
                   Class<?> c = Class.forName(args[0]);
                   Class[] argTypes = new Class[] { String[].class };
                   Method main = c.getDeclaredMethod("main", argTypes);
                   // String[] mainArgs = Arrays.copyOfRange(args, 1, args.length); //JDK 6
                   //jdk <6
                   String[] mainArgs = new String[args.length - 1];
                   for (int i = 0; i < mainArgs.length; i++) {
                        mainArgs[i] = args[i + 1];
                   main.invoke(null, (Object) mainArgs);
                   // production code should handle these exceptions more gracefully
              } catch (ClassNotFoundException x) {
                   x.printStackTrace();
              } catch (NoSuchMethodException x) {
                   x.printStackTrace();
              } catch (IllegalAccessException x) {
                   x.printStackTrace();
              } catch (InvocationTargetException x) {
                   x.printStackTrace();
              } catch (Exception e) {
                   e.printStackTrace();
    2 - create a .bat file:
    @echo off
    java -cp C:\Downloads\Marcxml\marc4j.jar; C:\Downloads\Marcxml\marcxml.jar; Executer %TARGET_CLASS% %IN_FILE% %OUT_FILE%3 - use set command to pass variable:
    Open MS-DOS, and type the following:
    set TARGET_CLASS=MyTargetClass
    set IN_FILE=in.txt
    set OUT_FILE=out.txt
    Then run your .bat file (in the same ms dos window)
    Hope that Helps

  • How to run a batch file using java

    Hi guys,
    I want to run a batch file by running a java program.
    i have tried for this code, but it is not working , plz guide me code.
    Runtime r = Runtime.getRuntime();
         Process p = null;
         try
              String[] cmd ={"cmd","/c","C:\\jarkarta-tomcat-3.2.3\\webapps\\DDS\\Resumes\\leap.bat"};
              p = r.exec(cmd);
         catch(Exception e)
         System.out.println("Exception in Runtime batch processing."+e);
         }

    You will need this:
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html

Maybe you are looking for