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

Similar Messages

  • How to capture output of java files using Runtime.exec

    Hi guys,
    I'm trying to capture output of java files using Runtime.exec but I don't know how. I keep receiving error message "java.lang.NoClassDefFoundError:" but I don't know how to :(
    import java.io.*;
    public class CmdExec {
      public CmdExec() {
      public static void main(String argv[]){
         try {
         String line;
         Runtime rt = Runtime.getRuntime();
         String[] cmd = new String[2];
         cmd[0] = "javac";
         cmd[1] = "I:\\My Documents\\My file\\CSM\\CSM00\\SmartQ\\src\\E.java";
         Process proc = rt.exec(cmd);
         cmd = new String[2];
         cmd[0] = "javac";
         cmd[1] = "I:\\My Documents\\My file\\CSM\\CSM00\\SmartQ\\src\\E";
         proc = rt.exec(cmd);
         //BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
         BufferedReader input = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
         while ((line = input.readLine()) != null) {
            System.out.println(line);
         input.close();
        catch (Exception err) {
         err.printStackTrace();
    public class E {
        public static void main(String[] args) {
            System.out.println("hello world!!!!");
    }Please help :)

    Javapedia: Classpath
    How Classes are Found
    Setting the class path (Windows)
    Setting the class path (Solaris/Linux)
    Understanding the Java ClassLoader
    java -cp .;<any other directories or jars> YourClassNameYou get a NoClassDefFoundError message because the JVM (Java Virtual Machine) can't find your class. The way to remedy this is to ensure that your class is included in the classpath. The example assumes that you are in the same directory as the class you're trying to run.
    javac -classpath .;<any additional jar files or directories> YourClassName.javaYou get a "cannot resolve symbol" message because the compiler can't find your class. The way to remedy this is to ensure that your class is included in the classpath. The example assumes that you are in the same directory as the class you're trying to run.

  • Trying to run external script using Runtime.exec

    Hey,
    I am trying to use Runtime.exec(cmd, evnp, dir) to execute a fortran program and get back its output, however it seems to always be hanging. Here is my code snippet :
                Process process = Runtime.getRuntime().exec(
                      "./fortranCodeName > inputFile.txt" , null, new File("/home/myRunDir/"));
                InputStream stream = new InputStream(process.getInputStream());
                InputStream error = new InputStreamr(process.getErrorStream());
                BufferedReader stdoutReader = new BufferedReader(new InputStreamReader(stream));
                BufferedReader erroutReader = new BufferedReader(new InputStreamReader(error));
                System.out.println(stream.available());  //returns 0
                System.out.println(error.available());     //returns 0
                while (true) {
                    String line1 = stdoutReader.readLine();  //hangs here
                    String line2 = erroutReader.readLine();
                    if (line1 == null) {
                        break;
                    System.out.println(line1);
                    System.out.println(line2);
                }I know for a fact that this fortran code prints out stuff when run it in terminal, but I don't know if I have even set up my Runtime.exec statement properly. I think I am clearing out my error and input streams with the whole reader.readLine bit I have above, but I am not sure. If you replace the command with something like "echo helloWorld" or "pwd", it prints out everything properly. I also am fairly confident that I have no environmental variables that are used in the fortran code, as I received it from another computer and haven't set up any in my bash profile.
    Any Ideas?

    Okay, so I implemented the changes from that website (thanks by the way for that link, it helps me understand this a little better). However, my problem is still occuring. Here is my new code:
                class StreamThread extends Thread {
                InputStream is;
                String type;
                StreamThread(InputStream is, String type)
                    this.is = is;
                    this.type = type;
                public void run()
                    try
                        InputStreamReader isr = new InputStreamReader(is); //never gets called
                        BufferedReader br = new BufferedReader(isr);
                        String line=null;
                        while ( (line = br.readLine()) != null)
                            System.out.println(type  +">"+  line);
                        } catch (IOException ioe)
                            ioe.printStackTrace();
            try {
                Process process = Runtime.getRuntime().exec(
                      "./fortranCodeName" , null, new File("/home/myRunDir/"));
                StreamThread stream = new StreamThread(process.getInputStream(), "OUTPUT");
                StreamThread errorStream = new StreamThread(process.getInputStream(), "ERROR");
                stream.start();
                errorStream.start();
                int exitVal = process.waitFor(); //hangs here
                System.out.println("ExitValue: " + exitVal);

  • How to run batch file using trigger?

    Hi, i am trying run a batch file using a trigger on a table.
    say i have a table XYZ(col_1 varchar2 primary key, col_2 varchar2)
    the values of col_2 keeps changing and col_1 are constant
    whenever the value of col_2 in any row changes from "on" to "off" i want to run a batch file C:\Users\ABC\Desktop\test.bat
    i did some searching but couldn't find any solution. Thanks in advance
    Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production

    >
    the script will be started around 60-70 times a day
    >
    No - as marwim said the script will be executed every time the trigger is fired. And that trigger, depending on how it is written, might be fired several times for the same transaction.
    And if the trigger is fired the script will be executed even if the transaction that caused the trigger to fire issues a ROLLBACK.
    Triggers are non-transactional. You need to clearly define the business rules for when the script should run. Should it run only when the transaction is COMMITTED? Or should it run if the transaction executes even if the transaction performs a ROLLBACK?
    A trigger is the wrong solution for your problem.
    Please clarify what the business rules are that should control the execution of the script.

  • Running batch files using java

    Hi,
    How can i run two batch files in a specified interval(Eg. 1 hour) using java.
    Thanks

    Hi,
    Learn to Use the API.
    import java.io.IOException;
    import java.util.Timer;
    import java.util.TimerTask;
    public class RunBat {
         static void runBatchFiles(String[] batchFiles)
              final String[] files = batchFiles;
              Timer timer = new Timer();
              TimerTask task = new TimerTask()          {               
                   Runtime r = Runtime.getRuntime();               
                   public void run() {
                        for(String command : files)
                             try {
                                  r.exec(command);
                             } catch (IOException e) {                              
                                  e.printStackTrace();
              timer.schedule(task, 1000, 1000*60*60);
         public static void main(String[] args) {
              runBatchFiles(new String[]{"cmd /C start f:/one.bat","cmd /C start f:/two.bat"});
    }Thanks

  • LabView equivalent to running batch files using the "shell" command (VisualBasic)

    I'm converting a VisualBasic app to LabView and am having trouble figuring out how to run a batch file with LabView.
    The VB code that I'm trying to replicate is:
    'UNLOAD RTX DRIVERS
    Dim ProcessId As Long
    ProcessId = Shell(App.Path + "\UnloadReloadRTX.bat", vbNormalFocus)
    Wait 400
    I haven't found a LabView equivalent to the Shell command. Any suggestions will be appreciated.
    thanks,
    Todd

    It seems as if this question pops up every week. Use the System Exec.vi found under Funtions - Communications palette. It is the equivalent of Shell.
    - tbob
    Inventor of the WORM Global

  • Running System commands using Runtime.exec()

    I'm trying to run an example from "The Java Programming Language" book by Arnold, Gosling and Holmes. I'm trying to run a system level command and get the results. The code looks like:
    public static String[] runCommand(String cmd) {
    String[] outputData= null;
    String[] cmdArray = {"/usr/bin/ls", "-l", "/tmp"};
    try {
    Process child = Runtime.getRuntime().exec(cmdArray);
    InputStream in = child.getInputStream();
    InputStreamReader reader = new InputStreamReader(output);
    BufferedReader = new BufferedReader(reader);
    // read the commands output
    int counter = 0;
    String line;
    while ((line = input.readLine()) != null)
    outputData[counter++]= line;
    if (child.waitFor() != 0){  // error when it's not 0       
    System.out.println("Couldn't run the command.");
    System.out.println("It produced the following error message : " + child.exitValue());
    outputData = null;
    } catch (Exception e){
    System.out.println("It got here!");
    System.out.println("It produced the following error message : " + e.getMessage());
    outputData = null;
    return outputData;
    It gets to the while line, trys to run the input.readLine() and kicks out the exception that looks like:
    It got here!
    It produced the following error message : null
    I know it gets to the input.readLine() because I had a whole lot more try blocks in there, but for simplicity left it out (so it look like the code in the book, which I tried originally). When I run the same command from the command line (on our Sun Solaris 2.8 system) I get results back. I'm not sure what I'm doing wrong. Any help would be greatly appreciated. Thanks.

    Hi, duffymo, hope you can help me. Consider this servlet code:
    String theCommand = "csh /export/home/gls03/sasstuff/runsas.csh /export/home/g
    ls03/sasstuff/gary2.sas";
    //Create a parent Process for the sas program subprocess:
    Process p = rt.exec(theCommand);
    System.out.println("after call to rt.exec(theCommand)");
    Here is the runsas.csh script:
    #!/bin/csh
    setenv LD_LIBRARY_PATH /opt/sybase/lib:/usr/lib:/usr/openwin/lib:/opt/SUNWspro/S
    C2.0.1
    setenv SASROOT /usr/local/CDC/SAS_8.2
    setenv XKEYSYMDB /usr/local/CDC/SAS_8.2/X11/resource_files/XKeysymDB
    $SASROOT/sas -sasuser /hpnpages/cgi-bin/applinks/hospcap/tmp $1
    The execution never gets to the println statment, here is the error:
    class java.io.IOException Exception. Message: CreateProcess: csh /export/home/g
    ls03/sasstuff/runsas.csh /export/home/gls03/sasstuff/gary2.sas error=2
    java.io.IOException: CreateProcess: csh /export/home/gls03/sasstuff/runsas.csh /
    export/home/gls03/sasstuff/gary2.sas error=2
    at java.lang.Win32Process.create(Native Method)
    at java.lang.Win32Process.<init>(Win32Process.java:66)
    at java.lang.Runtime.execInternal(Native Method)
    at java.lang.Runtime.exec(Runtime.java:551)
    at java.lang.Runtime.exec(Runtime.java:477)
    at java.lang.Runtime.exec(Runtime.java:443)
    at sasRunnerNew.doPost(sasRunnerNew.java:103)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:760)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubIm
    pl.java:262)
    at weblogic.servlet.internal.TailFilter.doFilter(TailFilter.java:21)
    at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.ja
    va:27)
    at us.ny.state.health.hin.hinutil.HinFilter.doFilter(HinFilter.java:124)
    at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.ja
    va:27)
    at weblogic.servlet.internal.WebAppServletContext.invokeServlet(WebAppSe
    rvletContext.java:2643)
    at weblogic.servlet.internal.ServletRequestImpl.execute(ServletRequestIm
    pl.java:2359)
    at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:139)
    at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:120)
    The command runs fine in unix.
    I've also tried using these as arguments to exec:
    String theCommand = "/bin/csh /export/home/gls03/sasstuff/runsas.csh /export/home/gls03/sasstuff/gary2.sas";
    String[] theCommand = {"csh", "/export/home/gls03/sasstuff/runsas.csh", "/export/home/gls03/sasstuff/gary2.sas"};
    These generate the same error. I'm thinking this is a sas-specific problem.
    Thanks for any help. Gary

  • Problem in running system commands using Runtime()

    hi,
    i am trying to run the "dir" command in windows OS using Runtime(). But while
    executing the program i am getting
    java.io.IOException: CreateProcess: dir error=2 error. But if i replace the "dir" command by "notepad" command its working fine. below is the source code.
    class testing
    public static void main(String args[])
         try{
    Runtime rt=Runtime.getRuntime();
    Process p=rt.exec("dir"); //Generating Errors
    //Process p=rt.exec("notepad"); //Working Fine
         }catch(Exception e){System.out.println(e);}
    }plzz help me out.
    thanx

    thats fine its working. i made two changes. First i used an array to send the
    arguments. if we directly use "cmd.exe /c dir" then its converting "/C" to "\C" thus
    producing the error. so i used
    Runtime rt=Runtime.getRuntime();
    String args1[]={"cmd.exe","/C","dir"};
    Process p=rt.exec(args1);But then i got no error no output. From other forums i came to know about capturing the data using input streams and i included the following code.
    BufferedReader Resultset = new BufferedReader
         (new InputStreamReader(p.getInputStream()));
    String line;
    while ((line = Resultset.readLine()) != null)
         {          System.out.println(line);          }Now its working fine. Thanx for ur help.

  • Problem to execute cvs command using Runtime.exec method

    Hello,
    I want execute this cvs command, with this options:
    cvs -d :pserver:[email protected]:/home/cvs/cvsroot rlog -S -d "2007/05/01<now" Project
    I tried to execute with Runtime.exec() :
    Runtime.exec("cvs -d :pserver:[email protected]:/home/cvs/cvsroot rlog -S -d \"2007/05/01<now\" Project");
    But I have an error because the smaller character is interpretate as a redirection, no as a smaller symbol.
    How I can do to use this command with Runtime.exec ?
    Thanks.
    Regards.

    Sorry,
    I had a typing mistake.
    I want say:
    Runtime.exec("cvs -d :pserver:[email protected]:/home/cvs/cvsroot rlog -S -d \"2007/05/01<now\" Project");
    Regards.

  • Run Batch file using GPO in all users with Windows 2008 R2

    Dear Sir,
    We have to install one software packages in all laptops using GPO. we have batch file and using this we can install software.
    is there any way to install automatic by this batch file?
    this is not msi packages.
    Regards,
    Sunil 
    SUNIL PATEL SYSTEM ADMINISTRATOR

    > Please provide how to configure...
    https://technet.microsoft.com/en-us/magazine/dd630947.aspx
    https://technet.microsoft.com/library/cc779329.aspx
    Greetings/Grüße,
    Martin
    Mal ein
    gutes Buch über GPOs lesen?
    Good or bad GPOs? - my blog…
    And if IT bothers me -
    coke bottle design refreshment (-:

  • Problem in opening a doc file using Runtime.exec()

    Code:
    import java.io.*;
    class StreamGobbler extends Thread {
        InputStream is;
        String type;
        StreamGobbler(InputStream is, String type) {
            this.is = is;
            this.type = type;
        public void run() {
            try {
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
                String line=null;
                while ( (line = br.readLine()) != null) System.out.println(type + ">" + line);   
            catch (IOException ioe) {
                 ioe.printStackTrace(); 
    public class GoodWindowsExec {
        public static void main(String args[]) {
             String file = "test.doc";
             String appPath = "/C";
            try {
                String osName = System.getProperty("os.name" );
                System.out.println("OS : " + osName);
                String[] cmd = new String[3];
                if( osName.equals( "Windows NT" ) || osName.equals( "Windows XP" )) {
                    cmd[0] = "cmd.exe" ;
                    cmd[1] = appPath;
                    cmd[2] = file;
                else if( osName.equals( "Windows 95" ) ) {
                    cmd[0] = "command.com" ;
                    cmd[1] = appPath;
                    cmd[2] = file;
                Runtime rt = Runtime.getRuntime();
                System.out.println("Execing " + cmd[0] + " " + cmd[1] + " " + cmd[2]);
                Process proc = rt.exec(cmd);
                // any error message?
                StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");           
                // any output?
                StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT");
                // kick them off
                errorGobbler.start();
                outputGobbler.start();
                // any error???
                int exitVal = proc.waitFor();
                System.out.println("ExitValue: " + exitVal);       
            catch (Throwable t) {
                t.printStackTrace();
    }I got this code from internet. Program will work fine if my "test.doc" is in "C:\test.doc" directory. Is there any way to get the application path and open the doc file or how to give a specified path for my doc file
    EG:- "C:\TestDir\test.doc"
    Thanks

    Well /C is not the path to the app. It is a switch to
    the command line.
    set your file name to "C:/test.doc"
    ~TimSorry, I guess my reply doesn't really answer the problem. But you can supply the entire path as part of the file name string.
    String file = "C:/Path/To/My/File/to execute/test.doc"

  • How to open an .txt file or .doc file using Runtime.exec()?

    Thanks

    Do:String[] cmdLineArray = new String[3];
    cmdLineArray[0] = "cmd.exe";
    cmdLineArray[1] = "/c";
    cmdLineArray[2] = yourCompletePathFile;
    Runtime.getRuntime().exec(cmdLineArray);

  • Running batch file

    Hi,
    i am running a batch file from a java program. But in the batch file, the home is set to a relative path like .. (two dots) and in the batch file i am yet setting the classpath for running another java application. the main class of the application is in the jar file set in the classpath and when i am trying to run the java program, when i call the batch file, using Runtime.exec(), it says no class def found error since it is unable to locate the main class specified in th jar file.
    can anybody suggest as to what i can do so that my application may run to ecexution.?
    Thanks

    Call a 'regular' java class from the JSP and read :
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps_p.html
    Keep in mind that possibly hundreds of client user threads will be accessing your JSP page...Are you going to run a batch file for each request that you receive?

  • How to run a batch file using tigger....

    Hi, i am trying run a batch file using a trigger on a table.
    say i have a table XYZ(col_1 varchar2 primary key, col_2 varchar2)
    the values of col_2 keeps changing and col_1 are constant
    whenever the value of col_2 in any row changes from "on" to "off" i want to run a batch file C:\Users\ABC\Desktop\test.bat
    i did some searching but couldn't find any solution. Thanks in advance
    Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production
    sorry wrong foum to post.
    will post in the correct one
    how to run batch file using trigger?

    Hallo,
    welcome to the forum.
    This is the forum for the tool {forum:id=260}. Your question should be placed in {forum:id=75} or {forum:id=61}.
    When you post your question there please provide additional information like db version, what kind of trigger you want to use, how you want to prevent the execution when the transaction is rolled back... {message:id=9360002}
    Regards
    Marcus

  • Using JSP to run batch file - command launches excel but doesn't open file

    I have written a jsp on a server which runs a batch file. Every command line in the batch works fine except the following:
    CALL "C:\Program Files\Microsoft Office\Office\Excel.exe" C:\Temp\spreadsheet.xls
    I can see that a command prompt has been opened and an instance of Excel has been created, but it does not open the file.
    I tried running the batch file on its own. It worked fine. I tried putting the java code in the jsp into a java class, that worked okay too. I think it might be to do with the fact that the client is trying lauch the application through the web, but it's missing some information such as paths.
    I am totally running out of ideas.. please help

    I guess if I know JSP stands for Java Server Pages..
    I would most probably know it runs on servers.Yes, you might, but if you were assuming that the path you gave would always lead to an executable running on the client you'd have a problem. It's worth asking.
    I must admit it's probably not the best idea, but if
    you can give me some advice on that, that would be
    greatJSPs shouldn't have code in them that doesn't pertain to view. I'd wrap something like a system call or Runtime.exec in a Java Bean that you can test off-line without the JSP. Then have the JSP instantiate an instance, invoke its method, and display the value that's returned.
    You've read this, of course:
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
    Everyone who uses Runtime.exec should.
    %

Maybe you are looking for

  • Application not working without restart the blackberry

    Dear All, when i get connected through WiFi , the only app working is the browser and the reset of the applications not working , and after restarting the blackberry phone every thing working fine for just 24 hours then it come back down again and i

  • Protective Case for 3Gs

    Hi all, Now that I have the new iphone 32G and like to protect it, what cases would people recommend? Real protection from dropping. I've seen some that doubles as a extra battery,etc. Also, for obvious reasons, it's probably going to be impossible f

  • Photshop Element 9 téléchargement de mise à jour incomplète

    Bonjour, Je possède Element 9 que j'utilise avec windows 7. Le logiciel m'indique qu'il y a une mise à jour et lorsque j'effectue le télécharchement de celle-ci je n'obtiens pas la totalité des fichiers.(erreur 16822) Pouvez-vous svp m'aider ??

  • 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

  • Generate-Script generates only create package not create or replace package

    Hello, I try do work with the Oracle Developer Tools for Visual Studio 2010 to include my PL/SQL-code in TFS. I have include all my PL/SQL-code in a Oracle-Projekt and check it in. Than I'm working with Visual Studio to update my packages. I open a p