Java.  Starting Batch files

Is it possible to run batch files from a java program?

Navigate yourself around pitfalls related to the Runtime.exec() method:
http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html

Similar Messages

  • Java and batch files

    i want to launch my application by a batch file, whit this script:
    @echo off
    "C:\j2sdk1.4.2_08\bin\java.exe" -cp "C:\Documents and Settings\Intrepido\Desktop\my tesina" BSServer 2103
    pause
    my application as first operation, read from a txt file some row just to configure himself.
    if i launch my application from DOS, writing the path manually, my application does function correctly, instead, launching it from batch file, the first row read return a null value; (i use the RandomAccessFile class and the readLine() method to access file...)
    moreover, since my application is a JFrame class, i've associate some icon to the buttons of the window. starting the application manually from DOS the icons are benn loaded, instead, launching the application from the batch file, the icons are not loaded...
    Help me please...
    and sorry for my bad english...

    i want to launch my application by a batch file, whit
    this script:
    @echo off
    "C:\j2sdk1.4.2_08\bin\java.exe" -cp "C:\Documents and
    Settings\Intrepido\Desktop\my tesina" BSServer 2103
    pause
    my application as first operation, read from a txt
    file some row just to configure himself.
    if i launch my application from DOS, writing the path
    manually, my application does function correctly,
    instead, launching it from batch file, the first row
    read return a null value; (i use the RandomAccessFile
    class and the readLine() method to access file...)
    moreover, since my application is a JFrame class,
    i've associate some icon to the buttons of the
    window. starting the application manually from DOS
    the icons are benn loaded, instead, launching the
    application from the batch file, the icons are not
    loaded...
    Help me please...
    and sorry for my bad english...Since it is a java forum, I suppose that your app is a java app, isn�t it?
    First, define the MANIFEST.MF of your application, that must call the class that contains the famous public static void main(String[] args) method. If you haven�t made this method yet, make it. This method must initialize your app. If you don�t know how to create or how to configure the MANIFEST.MF file, read the articles below:
    http://java.sun.com/developer/Books/javaprogramming/JAR/basics/manifest.html
    http://java.sun.com/j2se/1.3/docs/guide/jar/jar.html
    Don�t forget to configure the reference of some jar files required by your app in the MANIFEST.MF if it is necessary.
    Second, create the batch file. The content of this file is simple. It has has to be like below:
    java -jar MyJarFile.jar
    Where MyJarFile.jar is your jar file. Then, put this batch file in the same directory of the jar file and double click it. Finish! Your app will be executed as you want.
    Of course, first of all, you have to configure the java environment variables in order to this app works well (JAVA_HOME, PATH, CLASSPATH, etc).
    It is just one manner to do what you want. There are other ways to do it, of course.

  • Can Java execute batch file outside of current JVM in separate process tree

    Hi,
    Does anyone know how to run programs from Java as separate processes that will not die when the spawning java program exits (JVM exits).
    The problem I have with using Runtime.exec is it spawns only child processes under the current running JVM, thus when the origonal program that called Runtime.exec ends so does all child processes.
    Basically I want to start a DOS batch file from my Java application, my Java application will then immediately exit (calling System.exit(0) ). The batch program will continue to run, its does some file clean up, create's some new files and deletes the old jar (containing the main app), it then rebuilds the main app jar and and executes the main class and then exits itself.
    I've also tried the apache.tomcat.jni.Proc :-
    long pool = Pool.create( new Long(0).longValue() );
    long pa = Procattr.create( pool );
    Procattr.dirSet( pa, "c:\\temp\\updater\\");
    Procattr.cmdtypeSet( pa, Proc.APR_SHELLCM );
    Procattr.detachSet( pa, 1 );
    long proc = Proc.alloc( pool );
    Proc.create( proc, "test.bat", new String[]{"test.bat"}, null, pa, pool );
    System.exit(0);
    The detach option doesn't work, if I take it off then the bat file runs and stops the JVM exiting, if I leave it in the batch file never gets called.
    Is this possible in Java. Can java start master process on Windows XP JDK1.5+?
    Cheers
    Chris.

    Well I found the answer elsewhere (java.net) thought I'd post it here for future visitors who might be experience the same problem.
    Basically Runtime can do this however it must be done the following way :-
    The java:-
    public class Main {
        public static void main(String[] args) throws Exception {
            Process p=Runtime.getRuntime().exec("cmd /c c:\\test.bat");
            System.out.println("done");
            System.out.println("quitting");
            System.exit(0);
    }The batch:-
    @echo off
    PING 1.1.1.1 -n 1 -w 5000 >nul
    java -cp "c:\ " MainThe important line that makes the whole thing work is :-
    @echo offIf this line is missing then the whole things locks up (must be the io streams getting used)
    Also this code can not be run from an IDE (well at least not from Intellj) as it also locks up.
    It must be run from a command prompt or jar.
    Also note that any commands in the batch file must have there output redirected to "nul" otherwise Windows kills the cmd as soon as it trys to output to a dead stream (dead because the Java has exited). for example :-
    @echo off
    PING 1.1.1.1 -n 1 -w 10000 >nul
    cd %1
    del /F /Q *.* >nul
    move /Y new\*.* >nul
    RD /Q /S new >nul
    PING 1.1.1.1 -n 1 -w 1000 >nul
    java -cp "c:\ " Main
    exit

  • Java and Batch File Issue - need urgent help

    I have a java program which calls a batch file. This batch file calls another java program. I want an option so that I can close this java program from main program.
    If i try process.destroy then it will call batch file and not java program.
    I can't go away with batch file.
    I will appreciate if someone can help me.

    khannap wrote:
    Hi, Thanks for the help but this doesn't seem solving my problem completely. I will appreciate if you can help more.
    I will explain you the scenario -
    1. There is java program provided as an external program to me.Only changes things slightly.
    2. This java program is called using batch file. When batch file is started this java program starts and listens on a socket for incoming data.I would want to wrap the launch of this java program in another JVM so we can use process.destroy().
    3. I am writing a program to check performance of the above java program. I want to call this java program from my program in a loop having some varying config data. When I run the loop first time I create a batch file at run time which executes the batch file provided by vendor. This batch file starts the socket. Once my message list is over then my loop goes to executing the batch file again with different config parameters. But this time I run into issue because my previous java program is not killed after message sending was over.Would it be acceptable to mung the 3rd party batch file to insert a wrapper JVM?
    Even if i use threads I don't think I can get rid of batch file.I did not suggest getting rid of batch files.
    So, I need to find a way so that when any iteration of loop is over then this socket program is killed. These 3rd party java programs - do they not have a "terminate" command you can put at the end of your message list?
    Even if i closed the socket from my client program that doesn't help because server is still listening and waiting for new client.
    I need to kill server which was started by batch file.On Linux it would be fairly simple to modify your batch file to determine what the process id is and send the process a signal to terminate it.
    Not sure what you can do on Windows.

  • How do I start a batch file and check it's status?

    First of all I want to say I am a beginner in Java.
    I am working on an server side application that starts batch files (for database filling). After it starts the batch (.bat) file it has to check the status and write it in the database.
    The problem I run into the combination of starting the batch and checking the status.
    So far I have found out that I can run the batch file with starting up an process with the Runtime.getRuntime().exec command. What I haven't found out if it is posible to check the status of this proces in any way.
    I also found out that with using thread commands like isAlive I can check the status of a thread, but not of an process. And I understand that a thread can't start an batch file.
    So could anyone please help me on my way. Am I doing something wrong? Is any of the above info incorrect? Or am I on the right way? And if I am on the right way what is the next step? Thanx in advance.

    The problem I run into the combination of starting
    the batch and checking the status.The exit status is only set onve the process completes.
    process.exitStatus()
    I also found out that with using thread commands like
    isAlive I can check the status of a thread, but not
    of an process. And I understand that a thread can't
    start an batch file.Everything run in java is run from a thread. Only threads can do anything. The default thread is called "main"

  • To catch exception from a batch file

    Hi,
    I am running a batch file using java,the batch file is used for running SQL Loader.It is working OK,but I am unable to catch any exception or sucess message.Can anyone help?
    regards,
    Anshuman

    Have your Java main() catch Throwable and then use System.exit(an errror code); inside the catch. Your batch file can then examine the process return code.

  • Problem wiht Running Batch File using Runtime.exec()

    I am writting one program which will create a jar file using a windows Batch file.
    The main program is in the folder "d:\CmdExec.java".
    The other one to which a jar file to be created is in the folder "e:\folder\HelloWorld.class"
    The contents inside the "e:\folder" are
    e:\folder\HelloWorld.class
    e:\folder\mainClass.txt
    e:\folder\run.bat
    The mainClass.txt contains "Main-Class: HelloWorld"
    The Run.bat file contains "jar cmf mainClass.txt HelloWorld.jar *.class"
    The coding for CmdExec.java is as follows
    import java.io.*;
    import java.awt.Desktop;
    public class CmdExec {
    public static void main(String argv[]) {
    try {
    Desktop desktop = null;
    if (Desktop.isDesktopSupported()) {
    desktop = Desktop.getDesktop();
    desktop.open(new File("e:\\folder\\run.bat"));
    catch (Exception err) {
    err.printStackTrace();
    When i double click the file e:\folder\Run.bat, it will create a jar file for HelloWorld.class.
    But, i want to create that jar file using the java program CmdExec.java.
    When i run CmdExec.java, the batch file is opened. But it shows error as "Can't find the specified file"
    But when i copy the following files to "d:\",
    e:\folder\HelloWorld.class
    e:\folder\mainClass.txt
    the jar file is created using the CmdExec.java.
    But,
    e:\folder\HelloWorld.class
    e:\folder\mainClass.txt
    these files should be in the folder"e:\folder" only.
    Can anyone Help me this Problem?
    Or Anyother way for creating a jar file for one program by using another program?
    Help me soon.............

    Try this. It's not running a bat file. You can say it almost is a bat file.
    import java.io.*;
    import java.util.Scanner;
    public class CmdExec {
        public static void main(String argv[]) {
            try {
                Process p = Runtime.getRuntime().exec("jar cmf mainClass.txt HelloWorld.jar *.class");
                Scanner s1=new Scanner(new InputStreamReader(p.getInputStream()));
                while(s1.hasNextLine())
                    System.out.println(s1.nextLine());
                p.waitFor();
                System.out.println(p.exitValue());
                if(p.exitValue()==0)
                    System.out.println("Okay");
                else
                    System.out.println("Error");
            catch (Exception ex) {
                ex.printStackTrace();
    }Run it in the same folder as mainClass.txt
    Edited by: ColacX on Aug 1, 2008 10:35 AM

  • Batch file to start java application

    Hi All,
    I have created a batch file to start my application.
    startApp.bat
    javaw myclass
    But now the problem is the command prompt is not closing. I want the command prompt to close automatically. Any help??
    Thanks in Advance,
    Manjinder Singh

    I cannot use double click on JAR file as i have some other commands also inside batch file. Like classpath setting etc.
    I tried to use cmd /c myapp inside batch file, but still the command prompts stays there till i exit my application.
    Any further HELP??

  • Java.io.filepermission error while executing a batch file from java prog

    Hi,
    i want run a java program which executes a batch file, both are in a jar file. while am trying this using webstart it shows error:access denied java.io.filepermission <<ALL FILES>>execute. why this happens how to rectify this.
    By
    Vinod

    Clearly, it would be a security vulnerability to be able to do such a thing from the web w/o user granting trust to the application.
    Java Web Start applications run in the Java SE secure sandbox unless they have been granted all-permissions by the user:
    1.) sign all jar files.
    2.) add <security><all-permissions/></security> to the jnlp file.
    The user would then be prompted to grant trust to the applications.
    /Andy

  • Closing Console window while running Java application from Batch file

    Hi all,
    I have made a small application using Java swings,now i have made a jar file of my application and calling this jar file through batch file,when user clicks on that batch file it runs "java -jar applicationname.jar" command,but problem is that when i run that file from batch file it opens Dos console window at baclk of the screen which looks weird for a desktop application,i dnt want that Dos console window visible at the backend while my application is running,i have searched regarding this on google but found nothing usefull,if anybody can please help regarding that it will be a great releif for me,i have been stuck on this problem from last two days.
    Thanks.
    Simer

    warnerja wrote:
    georgemc wrote:
    warnerja wrote:
    start java -jar applicationname.jar
    That'll pop up another consoleI'm under the impression that the console window he is seeing is the one which cmd.exe opens when it is executing the batch file. And that batch file won't return until the java process has completed because he didn't start it in the background to let the batch file continue and terminate.
    So I don't think just simply substituting java with javaw will do much good either. Still think he needs a "start" command in that batch file.
    So now he can try:
    start java -jar ...
    or
    start javaw -jar ...Fair point

  • 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 Call a batch file from Java ?

    In my java application I have to call a .bat (Batch file) file.

    I found that already. Eventhough that is slightly differ from yours.
    .exec("cmd /c start x.bat");
    Anyhow
    Thanks yarr.
    My E-Mail ID is [email protected]

  • How to exit batch file after launching java application

    hello, I have created a simple java application and a batch file to launch the application. but when execute the batch file the application execute but the batch file still
    appear. I want to launch the application and immediately close the batch file after the application appears.
    Best Regards,
    Boulebtina

    In the batch script use the "START" command to start the program. To use it you need to have the script browse to the application directory first as shown below:
    c:
    cd MyApplication\ApplicationFolder
    START myApp.exe
    exitThis will start an application that is stored in C:\MyApplication\ApplicationFolder\myApp.exe. I use this quite a bit and works well for me.

  • How to execute java batch file in JSP

    Kindly give a solution. I want execute a batch file which gives a preview window ,. I want call that batch file in my jsp, .I am using Tomcat 5.5, I have tried that using a Process object and Runtime.getRuntime().exec(path) , where path is location of my batch file. As a java class i could execute the batch file, but when i import the method in JSP nothing is happening (even no jsp error).
    Is it possible to execute the batch file in JSP?
    Can any one help me?

    itsdhanasaraa wrote:
    But as this a web application ... By using Runtime i'm getting some probs ..
    Let me guess, you want your web application to run a program on the client and to your surprise that's not working?
    Ain't gonna happen.
    its taking more time to execute .... that's y is there any other option to execute .exe file other than Runtime.getRuntime().exec("filename");Write proper English and you may be taken more seriously.
    1) it's not "taking more time to execute", whatever that's supposed to mean.
    2) there's no other way to execute something. Not that you should every use even that way anyway
    3) whenever you start thinking of executing external programs from Java, start thinking of not using Java in the first place.

  • Batch file to start and stop

    Hi All,
    Can we create a batch file to start and stop the services. I need to start all the services like shared, essbase, eas, planning, webanlysis and financial reporting, and at also need to stop them using windows batch file.(Using windows 2003 server....service pack 1). Any help would be appreciated.
    Thanks

    Hi,
    The simplest script would be something like this. Save it as a .bat file, set all your services to manual and then set up a scheduled task to run this script when the computer starts.
    Gee
    ::          Startup Script for Hyperion Services          ::
    date/t >> startup.log
    time/t >> startup.log
    echo "Starting Hyperion Services" >> startup.log
    net start "Hyperion S9 OpenLDAP" >> startup.log
    net start "Hyperion S9 Shared Services" >> startup.log
    :: Insert pause of 5 seconds to ensure HSS has finished starting
    ping localhost -n 6 >nul
    net start "Hyperion S9 BI+ Analytic Services 9.3.1 - Essbase" >> startup.log
    net start "Hyperion S9 Administration Services ATS5" >> startup.log
    net start "HyperionRMIRegistry" >> startup.log
    net start "Hyperion S9 Planning" >> startup.log
    net start "Hyperion S9 Provider Services ATS5" >> startup.log
    net start "Hyperion S9 Apache 2.0" >> startup.log
    net start "Hyperion S9 BI+ 9.3 Core Services 1" >> startup.log
    :: Insert pause of 10 seconds to ensure Core has finished starting
    ping localhost -n 11 >nul
    net start "Hyperion S9 BI+ 9.3 Workspace" >> startup.log
    net start "Hyperion S9 BI+ 9.3 Financial Reporting Java RMI Registry" >> startup.log
    net start "Hyperion S9 BI+ 9.3 Financial Reporting Print Server" >> startup.log
    net start "Hyperion S9 BI+ 9.3 Financial Reporting Report Server" >> startup.log
    net start "Hyperion S9 BI+ 9.3 Financial Reporting Scheduler Server" >> startup.log
    net start "Hyperion S9 BI+ 9.3 Financial Reporting Web application" >> startup.log
    net start "Hyperion S9 BI+ 9.3 Web Analysis" >> startup.log
    date/t >> startup.log
    time/t >> startup.log
    echo "Finished Starting Hyperion Services" >> startup.log
    echo "###################################################################" >> startup.log

Maybe you are looking for

  • MOVED: need help overclocking on MSI X48C Platinum please

    This topic has been moved to Overclockers & Modding Corner. https://forum-en.msi.com/index.php?topic=120153.0

  • Link to purchse order for Doc in DMS

    Hello all ! I´m looking for a solution to link a document via DMS to a purachse order !? There is a letter sign (button) in the PO, I want find the linked doc there. It is posible for me to link the doc to material, equipment and others but I do not

  • Error when running "Run as" Java application from NWDS

    Dear All, I am trying to run the following .java proggie... Thanks for that. By the way, I am now trying to compile the following .java program..... Created on 01-Oct-2007 To change the template for this generated file go to Window>Preferences>Java>C

  • Enabling layer object  outlining on object like CS5?

    Is there a way to enable layer selection by locking the object? Example, in CS5.5 when you selected on an object (say a text box inside a circle) it would automatically select that layer so you an move it. IN CS6 you have to select the layer from the

  • Forcing char to be unsigned

    I am looking for a way to tell the compiler to handle all char as unsigned char. We are porting a lot of sources, and in all or other compiler we use a flag to have all characters treated as unsigned char. In the code a lot constructions occur where