How to invoke the .bat(batch file ) from the java program

i want to run some commands when i run one java program.
I wrote those dos commands on the batch file and i want to include the bat file in the java program so that i can execute the bat file when i run the java program.
tell me the way that i can run my bat file inside the java program.

i tried this :
a .bat file named test.bat, with this code : copy test.bat test2.bat
a java class, Test.class, in the same directory
public class Test {
     public static void main(String[] args) {
          try {           
               Runtime rt = Runtime.getRuntime();
               Process proc = rt.exec("cmd /c test.bat");
               proc.waitFor();
               int exitVal = proc.exitValue();
               System.out.println("Process exitValue: " + exitVal);
          catch (Throwable t) {
               t.printStackTrace();
}

Similar Messages

  • How can I execute a batch file from my java program

    Hi,
    Can someone help me or direct me to a link,
    How can I execute a DOS batch file from my java program?
    Thanks

    You will need to grab a handle to the process's
    outputstream so u can see its output.The OP didn't mention any output from any batch file;
    nor any input for that
    matter,so lets not complicate matters here for now
    ok?Actually I think this is essential to see whether it works or not. It's either that or do some manual check to see whether it ran, which is not exactly elegant, and in some cases this may not be easier than simply writing the output stream code, or in fact it may be impossible to check manually.
    I'm sure it wasn't intentional that your post appeared to be bristling with attitude.

  • How do I call another exe file from a Java program?

    Hi,
    I am doing a simple IDE (text editor/interpreter) for a simple programming language we are developing. It will be submitted as our project for this semester. I created an exe file (in C) which will be used as the interpreter. How do I call the interpreter from my IDE? The interpreter should run when the user clicks a button (i.e. the "Run" button). I've tried the Java Runtime class but it doesn't work. Anyone who knows how to do it?
    Thanks!

    I first tried to do a simple program that calls system commands such as dir, cd <dir>, etc.
    I do not have the exact code right now but as far as I can remember, here's what I wrote:
    class Sample{
        public static void main(String args[]) throws IOException{
           BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
           String command;
           while ((command = in.readLine()).equalsIgnoreCase("exit") == false){
              try{
                Runtime.getRuntime().exec(command);
              }catch(Exception e){
                 System.err.println("Error: " + e);
          System.exit(0);
    }

  • How do I run an exe file from a java program?

    I need to run an exe program from within a java program.
    what do I need to do this?
    thanks

    See java.lang.Runtime.exec()

  • How to compile and run a .java file from another java program

    hello,
    can any one tell me how to compile and run a *.java* file from another java program which is not in same directory?

    Well a smarter way of implementing this is by using a solution provided by Java Itself.
    If you are using J2SE 6.0+ there is an in built solution provided along with JDK itself and inorder to go ahead with solution the below are set of API which you;d be using it for compiling Java Programs (Files)
    http://java.sun.com/javase/6/docs/api/javax/tools/package-summary.html
    How do i do that ??
    Check out the below articles which would help you of how to do that
    http://www.ibm.com/developerworks/java/library/j-jcomp/index.html
    http://www.javabeat.net/javabeat/java6/articles/java_6_0_compiler_api_1.php
    http://books.google.com/books?id=WVbpv8SQpkEC&pg=PA155&lpg=PA155&dq=%22javax+tools%22+compiling+java+file&source=web&ots=XOt0siYe-f&sig=HH27ovuwvJgklIf8omTykUmy-eM
    Now once we are done with compilation.In order to run a Specific class all you ought to do is create an object and its specific methods of a specified class included in the CLASSPATH which you can manage it easily by usage little bit reflections.
    Hope that might help :)
    REGARDS,
    RaHuL

  • How to write the java program to retrieve the last 7 days dates

    Hi,
    I am having requirement that how to write the java program to retrieve the last 7 days dates. Please help me.
    Regards,
    Ahamad

    It needs any jar file.Of course!
    I did using jscape.My program is running fine.But it
    requires jar file.Which is licensed version.Maybe you should follow the link the the 'license' on the site I posted!
    >
    I have the doubt is apache provides jar file free
    versionMaybe you should follow the link the the 'license' on the site I posted!

  • How to open an MS-Word-File from a Java-Applikation ?

    Hi,
    i want to open an MS-Word-File from a Java-Applikation.
    Something like this:
    File myFile = new File("myFile.doc");
    myFile.open(); //unfortunately this methode doesn't exist
    Thanks for response

    In my opinion you have to use the Runtime.exec(String) method. I do not know the program name for msword.
    You can open a file in notepad by invoking the method Runtime.getRuntime().exec("notepad c:/xyz/abc.txt");
    Runtime runTime = Runtime.getRuntime();
    runTime.exec("programName" + " " + file);
    Of course the computer on which the program runs must have the application!
    Hope this helps!

  • Windows task scheduler to run batch file running a java program

    I have created a batch file that runs my SendEmail program. The batch file is in the same directory as the java program. The only line in the batch file is
    java SendEmail
    This works fine from the command prompt but from the windows task scheduler it fails to function. Any help on how I can overcome this problem will be greatly appreciated.
    THanks

    Looks okay. The classpath is set, too, I guess? Btw, try running javaw instead of java. I may err, but I think it can show a console, so you can watch any error messages.

  • Running Batch file thru a java program

    hai friends
    i have a batch file like hello.bat
    how can i run that batch file when i run my java program
    i heard that Runtime.exec() is used to run the batch files.
    can i use Runtime.exec() to run my hello.bat file or any other things i need to use ?
    Thankyou VeryMuch
    Yours
    Rajesh

    Yes, you can use Runtime. You should look it up in your API guide, but this code might get your started:
            try
                Process p = runtime.exec("command.com /c c:\\hello.bat");
            catch(IOException e)
                System.out.println("Failed");
            }Your API guide will explain how to get a Runtime object. The syntax is very straightforward.

  • How to abend the java program -if the condition fails

    Hi
    My program counts the number of headers in the input file and if the condition fails to satisfy the number we expected , it should comeout of the java program . Is their a specific statement to abend the program in java .
    if(columnCount == 5)
    // do all the steps
    else
    //abend the program }
    how to do that .... is it System.exit(1) or anything else
    thanks..
    Edited by: 1sai on Apr 23, 2009 6:52 PM

    BigDaddyLoveHandles wrote:
    It must have been that the [card sorters|http://en.wikipedia.org/wiki/Card_sorter] were making such a ruckus that I didn't hear it. The model 84 -- 2,000 cards a minute? -- d&auml;mn, that's sweet.
    I remember the first time I saw a card sorter in action, thinking it was kind of cool.
    I also think the teacher used it to describe some sorting algorithm, maybe radix sort??
    You've got me thinking, that might be part of the problem with computing today, not enough moving parts. No big tape drives spinning and oscillating. And few if any line printers anymore. Now there's an interesting piece of equipment.

  • Creating a file from a Java Program

    Hi all,
    if I want to store a byte array to a file somewhere in the middle of my program... is it possible to create the file inside my Java program, i.e. the file will be created during the execution of my program, and then write this byte array into it? The name of the file to be created is predefined by me, and not thru user input.
    If so, does anyone have a sample source code to show me? or redirect me to somewhere ?
    Thanks in advance!
    Joe

    You can take a look at the File, FileOutputStream, FileInputStream classes. A simple one will be like:
    byte[] ar = {12,13,14};
    File file = new File("wee.dat");
    if (!file.exists())
    try
    FileOutputStream fos = new FileOutputStream(file);
    fos.write(ar);
    }catch (IOException io){}
    else
    ...

  • Iam not able to run a simple batch file from within java

    This is how my code looks like.
    It does'nt give me any error but I dont see the output from batch file which is suposed to be a simple redirection of dir command...
    package mypackage1;
    import java.io.File;
    public class RunBatch
    public RunBatch()
    try{
    Runtime rt = Runtime.getRuntime();
    String cmd = "generate_invoice";
    String path = "C:\\application\\Maps\\Reports";
    File file = new File(path);
    String[] envp = {""};
    String[] args = {"C:\\application\\Maps\\Reports\\generate_invoice.bat"};
    System.out.println("************ executing batch ");
    Process proc = rt.exec(args);
    System.out.println("************ batch executed ");
    }catch(Exception e)
    e.printStackTrace();
    * @param args
    public static void main(String[] args)
    RunBatch runBatch = new RunBatch();
    }

    Runtime.exec() only can run executable files. Batch file is not an executable - it is a script executed by command interpreter (cmd.exe). So, you should execute "c:\windows\system32\cmd.exe /c C:\application\Maps\Reports\generate_invoice.bat".
    Denis
    http://www.excelsior-usa.com/jet.html
    JVM with AOT compilation

  • How to send a file from a java program to a servlet and get a response

    Hi,
    How can I call a servlet from a standalone java program and send a file to a servlet using POST method and in return gets the status back from the servlet. Any help is appreciated any small sample will help.
    Thanks.

    Hi,
    I am trying the following sample I got from net and am getting the following error. Any help what I am doing wrongs:
    06/12/24 02:15:58 org.apache.commons.fileupload.FileUploadBase$InvalidContentTypeException: the request doesn't contain a multipart/form-data or multipart/mixed stream, content type header is null
    06/12/24 02:15:58      at org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:294)
    06/12/24 02:15:58      at org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:268)
    06/12/24 02:15:58      at mypackage9.Servlet1.doPost(Servlet1.java:38)
    06/12/24 02:15:58      at javax.servlet.http.HttpServlet.service(HttpServlet.java:760)
    06/12/24 02:15:58      at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
    06/12/24 02:15:58      at com.evermind.server.http.ResourceFilterChain.doFilter(ResourceFilterChain.java:65)
    06/12/24 02:15:58      at oracle.security.jazn.oc4j.JAZNFilter.doFilter(Unknown Source)
    06/12/24 02:15:58      at com.evermind.server.http.ServletRequestDispatcher.invoke(ServletRequestDispatcher.java:663)
    06/12/24 02:15:58      at com.evermind.server.http.ServletRequestDispatcher.forwardInternal(ServletRequestDispatcher.java:330)
    06/12/24 02:15:58      at com.evermind.server.http.HttpRequestHandler.processRequest(HttpRequestHandler.java:830)
    06/12/24 02:15:58      at com.evermind.server.http.HttpRequestHandler.run(HttpRequestHandler.java:285)
    06/12/24 02:15:58      at com.evermind.server.http.HttpRequestHandler.run(HttpRequestHandler.java:126)
    06/12/24 02:15:58      at com.evermind.util.ReleasableResourcePooledExecutor$MyWorker.run(ReleasableResourcePooledExecutor.java:192)
    06/12/24 02:15:58      at java.lang.Thread.run(Thread.java:534)Here is the sample client code:
    import org.apache.commons.httpclient.HttpClient;
    import org.apache.commons.httpclient.methods.PostMethod;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    public class PostAFile {
        private static String url =
             "http://192.168.0.17:8988/Vulcan_Materials-ServletPost2-context-root/servlet/Servlet1";
        public static void main(String[] args) throws IOException {
            HttpClient client = new HttpClient();
            PostMethod postMethod = new PostMethod(url);
            client.setConnectionTimeout(8000);
            File f = new File("C:\\load.txt");
            System.out.println("File Length = " + f.length());
            postMethod.setRequestBody(new FileInputStream(f));
            int statusCode1 = client.executeMethod(postMethod);
            System.out.println("statusLine>>>" + postMethod.getStatusLine());
            postMethod.releaseConnection();
    }Here is the sample servlet code:
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.PrintWriter;
    import java.io.IOException;
    import org.apache.commons.fileupload.DiskFileUpload;
    import org.apache.commons.fileupload.FileItem;
    import java.util.List;
    import java.util.Iterator;
    import java.io.File;
    public class Servlet1 extends HttpServlet
      private static final String CONTENT_TYPE = "text/html; charset=windows-1252";
      public void init(ServletConfig config) throws ServletException
        super.init(config);
      public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
        try
          response.setContentType(CONTENT_TYPE);
          PrintWriter out = response.getWriter();
          java.util.Enumeration e= request.getHeaderNames();
            while (e.hasMoreElements()) {
              String headerName=(String)e.nextElement();
              System.out.println(headerName +" = "+request.getHeader(headerName));
           //System.out.println("Content Type ="+request.getContentType());
            DiskFileUpload fu = new DiskFileUpload();
            // If file size exceeds, a FileUploadException will be thrown
            fu.setSizeMax(1000000);
            List fileItems = fu.parseRequest(request);
            Iterator itr = fileItems.iterator();
    System.out.println("***************************");
            while(itr.hasNext()) {
              FileItem fi = (FileItem)itr.next();
              //Check if not form field so as to only handle the file inputs
              //else condition handles the submit button input
              if(!fi.isFormField())
                System.out.println("\nNAME: "+fi.getName());
                System.out.println("SIZE: "+fi.getSize());
                //System.out.println(fi.getOutputStream().toString());
                File fNew= new File("C:\\", fi.getName());
                System.out.println(fNew.getAbsolutePath());
                fi.write(fNew);
              else
                System.out.println("Field ="+fi.getFieldName());
            out.println("SUCCESS123456: ");
          out.close();
        catch(Exception e)
          e.printStackTrace();
    }Any help on what is wrong.
    Thanks

  • How to create a batch file for a java program?

    I have a java project in JCreator and the project is organised into packages. I have also configured JCreator to provide 2 arguments to the main method when the project is executed.
    I would want to create a batch file (.bat) for this project where the batch file can automatically use the arguments set in JCreator when the program runs.
    How do I go about creating the batch file?

    where the batch file can automatically use the arguments set in JCreatorThat all depends JCreator... can you get those arguments somehow?

  • How i invoke the c program?

    My question is occured during the program call the cmd.exe in windows or gnome-terminal in linux.I want the program to invoke a terminal and then execute the command on the terminal later defined by the program.The process is like that a you compile and executive a exe file . Visual c++ will executive your exe file in a terminal and in the terminal you can input the required value and get the result.The executive process is like that you run the exe file straightly in the terminal,it can provide a prompt to input the new value and it can output the result too. In my option ,I want to obstain the goal. I had tried it with Runtime.exec() but failed at last.
    So i'm very puzzled about how to obstain the aim.

    if it must be run in a completely separate terminal, you could use this in windows
    String program = ...
    String[] cmd = {"cmd", "/c", "start", "/MIN", program};
    Runtime.getRuntime().exec(cmd);Otherwise you could use the input/output streams from the process to get/send information to the program

Maybe you are looking for

  • HT4245 FACETIME IS NOT WORKING AFTER UPDATE TO IOS 6.1 ON IPHONE 5

    Did anyone have this problem? My facetime has not been working a week or so of updating my iPhone to ios 6.1. I've checked that facetime is on in my settings, have switched the phone off and on, still no luck! Please help..

  • WD Java iView button disappears

    Hello All, We have a Webdynpro Standard iView for ESS/ MSS , we are facing the followig scenario as follows the iView is getting display in the iView content area in the portal .  We have a system tray being enabled , now when we minimise and them ma

  • Apple Care *****

    I took my 17" Powerbook into the Apple Store locally. The problem was that my PB wasn't charging when it was connected to the charger unless you held it a certain way. They fixed that by providing me with a new adapter and also replacing my DC board.

  • Video format that supports iTunes- appleTV streaming AND DLNA

    I have both DLNA support and an Apple TV. I've been converting my dvds to mp4 so I can stream via iTunes to my TV,,Unfortunately mp4 is not compatible with DLNA (mpeg2). Is there a video/audio format, or a software solution, that will work? Of course

  • Unable to read french characters

    Im trying to reach data from an excel (using the Apache software's excel reader code) but my java code is not recognizing words like "D�cor". It is replacing '�' with '?'(All my columns are in English , it is just a couple of data entires like D�cor