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

Similar Messages

  • 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

  • Executing Batch files from Runtime.getRuntime().exec

    Can we execute batch files from Runtime.getRuntime().exec() method.
    Regards,
    Nalini

    hi,
    import java.io.IOException;
    class BatchFileTest{
         public static void main(String args[]){
              try{
              Runtime r = Runtime.getRuntime();
              Process p = r.exec("startcmd.bat");
              catch(IOException en){
                   en.printStackTrace();
    -Regards
    Manikantan

  • 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.

  • Running batch files thraugh java by passing parameters

    Hi
    I want to run a batch file by passing some parameters.
    Eg: copy.bat "D:\live\hoe.txt" "D:\test"
    while doing this from command prompt its working and i have written some java code for running this batch file.
    String live="D:\\live\\how.txt";
    String test="D:\\test";
    String bat="D:\\copy.bat";
    String[] command = new String[3];
    command[0] = bat;
    command[1] = live;
    command[2] = test;
    try {
    Runtime.getRuntime().exec(command);
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    but this time its not copying the file;
    Please help.

    Just another cross poster.
    [http://www.java-forums.org/new-java/15005-running-batch-files-thraugh-java-passing-parameters.html]
    db

  • Running exe files from java applications

    Hello All,
    Is it possible to run executable files from java applications?
    I need to run an exe file on the client from the server machine, the exe could reside on either the server or any other machine on the LAN. Is it possible to specify the path of where the exe resides, and run it on a client machine?

    HI,
    I tried to launch a MS Word application using runtime.exec but it gives me some problem
    The foll. code to launch a txt file using notepad works.
    Runtime rt = Runtime.getRuntime();
    String[] callAndArgs = {"notepad.exe","C:\\coo7\\wizard.txt"};
    Process child = rt.exec(callAndArgs);
    However, oif I try to launch a MS Word application, it asks for the entire path of WINWORD.exe, (unlike just specifying notepad.exe as the first argument in String[] callAndArgs) and this can vary from one machine to another.. how do I get around this?
    The foll. code snippet works but the complete path of where WINWORD.exe might be installed on any machine, is not fixed:-(
    Runtime rt = Runtime.getRuntime();
    String[] callAndArgs = {"C:\\Program Files\\Office\\Office10\\WINWORD.exe","C:\\coo7\\wizard.doc"};
    Process child = rt.exec(callAndArgs);
    Any idea/suggestions pls..

  • Running  .nsi file from java

    hi,
    Ho to run .nsi file from java.
    thanks in advance.

    User845466 wrote:
    Ho to run .nsi file from java.Find the program hanling that kind of documents an launch this via Runtime.exec() giving it your *.nsi file as a parameter.
    bye
    TPD

  • How to run batch file from oracle forms 9i

    Hi everyone.
    i have a data in csv file. i want to upload it to my database. i am using sql loader for it.
    i have made a batch file which run the sql loader and transfer my data to database.
    How to run batch file from oracle forms 9i.
    when i press the button, nothing uploads in my database. (when i simply run the batch file it works).
    here is my code
    Begin
    HOST('C:\temp\batchfile.bat');
    message('done');
    end;
    Thanks in advance
    regards
    sajid

    this is my log file, when i run manually.
    SQL*Loader: Release 10.2.0.1.0 - Production on Thu Jul 1 23:27:53 2010
    Copyright (c) 1982, 2005, Oracle. All rights reserved.
    Control File: file_to_upload.ctl
    There are 2 data files:
    Data File: sk.csv
    Bad File: sk.bad
    Discard File: none specified
    (Allow all discards)
    Data File: sk1.csv
    Bad File: sk1.bad
    Discard File: none specified
    (Allow all discards)
    Number to load: ALL
    Number to skip: 0
    Errors allowed: 50
    Bind array: 64 rows, maximum of 256000 bytes
    Continuation: none specified
    Path used: Conventional
    Table KHAN, loaded from every logical record.
    Insert option in effect for this table: APPEND
    Column Name Position Len Term Encl Datatype
    SR FIRST * , O(") CHARACTER
    DATES NEXT * , O(") CHARACTER
    AGENT NEXT * , O(") CHARACTER
    COUNTRY NEXT * , O(") CHARACTER
    TRANSACTIONS NEXT * , O(") CHARACTER
    PKR NEXT * , O(") CHARACTER
    USD NEXT * , O(") CHARACTER
    BANK NEXT * , O(") CHARACTER
    Table KHAN:
    11088 Rows successfully loaded.
    0 Rows not loaded due to data errors.
    0 Rows not loaded because all WHEN clauses were failed.
    0 Rows not loaded because all fields were null.
    Space allocated for bind array: 132096 bytes(64 rows)
    Read buffer bytes: 1048576
    Total logical records skipped: 0
    Total logical records read: 11088
    Total logical records rejected: 0
    Total logical records discarded: 0
    Run began on Thu Jul 01 23:27:53 2010
    Run ended on Thu Jul 01 23:27:54 2010
    Elapsed time was: 00:00:00.63
    CPU time was: 00:00:00.17

  • 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

  • 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\...

  • 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

  • Executing batch files from websevice using ODI OS Command

    Hi,
    Is it possible to execute the batch files using odi os command from webservices.
    We have developed a webservice, which passess some parameters to one batch file and after that we executing the same batch file in package using odi os command. In opeartor is showing as running, it never ends.
    But if we run the same package from designer, it is executing successfully. Also the same web service is working fine for executing non batch scenarios.
    what could be the problem??
    We got one possible reason for failure...
    For executing the batch from web services, we need read and executable permissions on the drive where batch sits.
    We are logging into ODI using SUPERVISOR. How to give the permissions to SUPERVISOR as we are having windows authentication.
    Edited by: Naveen Suram on Dec 17, 2009 8:07 PM
    As a work around, can we use ODIOSCommand instead of OS Command. But it is asking for starting event? Whether both the commands does the same functionality??
    Edited by: Naveen Suram on Dec 17, 2009 9:08 PM

    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 BAT file from Java

    how would i go about calling a batch file in java?
    a button is clicked that says "RUN" and then I want to run a batch file

    Hi !!!
    Im new to this forums but I think I can help you
    You can execute a separate process by using the class Runtime. In this example I execute one batch file located on the same directory the Java App is in.
    class Test
         public static void main(String a[])
              System.out.println("Executing Batch File");
              try{
              Runtime.getRuntime().exec("Runme.bat");
              catch(Exception ex){}
    }I hope that could help
    see
    how would i go about calling a batch file in java?
    a button is clicked that says "RUN" and then I want to
    run a batch file

  • How to run perl file from java file..???

    Hi All,
    How to run a perl file from java file.I know that there is one JPL(Java-Perl Library) preprocessor which can be used to do this,but no idea of how to do it..
    Any help is appreciated.
    Thanks in advance.

    viswa07 wrote:
    Ok and any idea regarding JPL..????I don't know it and the first few posts that I found mentioned it using Java 1.1-style JNI calls, which hints at a dead project. And you don't want to use a dead project.

  • How to Run Batch files from inside Reports.

    Hi All,
    I have 2 questions.
    1) How to change the direction of the reports with Arabic orientation i.e Right to left Change without changing the registry.
    2) How to execute a batch file from report or before execution of the report i.e before opening the report.
    I want to set few environmental variables before opening the report. How do i achieve this?
    Request the forum community to discuss and help me out on this issue.
    Thanks in advance

    Thanks Inol
    Though my report is running NLS variable values given in the batch file is not getting picked.
    Here is my batch file contents. My NLS Variables are not getting picked in the reports. I want that to be picked up and the reports orientation should change automatically as per the NLS variables given in the batch file.
    Please go through my batch file code.
    set NLS_LANG                   = AMERICAN_AMERICA.UTF8
    set NLS_CALENDAR            = GREGORIAN
    set NLS_DATE_FORMAT      = dd/MON/yyyy
    set FORMS60_PATH           =   <Enter Relevant Path>
    set REPORTS60_PATH        =  <Enter Relevant Path>
    set PATH=%PATH%;c:\forms6i\bin
    set ORACLE_HOME             =   c:\forms6i
    set TNS_ADMIN                 =   c:\forms6i\NET80\ADMIN\TNSNAMES.ORA
    rwrun60.exe d:\DOTNETORION17_bin\elist_rg1.rdf userid=scott/tiger@thai P1=10Please help me out in getting this value picked and run the report.

Maybe you are looking for

  • Adobe Photoshop Elements 10 wont open

    Ive intalled the Adobe Photoshop Elements 10 but when i go to open the program it says it cant find the shortcut. How do i open up the program now?

  • SSL error code -1/1/336032856 (Svn + apache + openssl-1.0.0-2) SOLVED

    The problem is that when I try to commit, checkout or even look inside a repo using Subclipse in Eclipse I get this error: commit -m "Added controls." (10 paths specified) RA layer request failed svn: Commit failed (details follow): svn: OPTIONS of '

  • Apple Application Support directory location?

    Hi, I have installed the new Safari 5.1.4 for Windows 7, but I couldn't locate the Apple Application Support directory under Program Files\Common Files\Apple. I have a older version of Safari installed on my other machine and it has the Apple Applica

  • Imovie 11 : problem with black photos

         Hello, I have some very dark photo in my Imovie project, good resolution, and in the timeline are displayed correctly. When I export the project these photo become of less quality and they loose their definition, the black color is not well disp

  • PSA - Name of object - *pa and *ob

    Hello, we have a process chain which contains a delete job for PSA. Within this process there is following: Name of PSA table: ZBW_UM1_PA and Name of PSA talbe: ZBW_UM1_OB Question: What is *PA and *OB ? Thanks in advance. Points will assigned if the