Runtime.exec() batch file problem

Hi folks,
i have a little problem when I want to execute a batch file through java's runtime.exec() method.
the execution of a very simple batchfile works (for example opening notepad or other stuff), but I have problems with the following batch file (although it's still simple):
net use s: \\Dd-nt-fs\Dsmp15_files
set DSCFG=c:\dscfg
set PSPATH=c:\adproof
set ora_path=C:\oracle\ora92
set path=S:\Dsmp_Q4_2004\Bin;%ora_path%\bin;%path%;
set nd_font=S:\Dsmp_Q4_2004\Fonts
set nxPS_FONT_DIR=%ND_FONT%
set PSPATH=c:\adproof
set PSFORMS=S:\Dsmp_Q4_2004\PsForms\Telenor
s:
cd S:\Dsmp_Q4_2004\bin
S:\Dsmp_Q4_2004\Dsmp_Reports\Telenor\adproof.exe DBUSER=a_user DBPSWD=a_pswd DBSTR=dbstr ADINFO=adinfo.lst TASKID=a_taskid
my guess is that there is a problem with the setting of environment variables which correspond to the drive s:
I mannually added the batchfile (line by line) and looked whether it got through to the command which executes the adproof.exe file: for example the below batchfile worked:
set DSCFG=c:\dscfg
set PSPATH=c:\adproof
set ora_path=C:\oracle\ora92
s:
cd S:\Dsmp_Q4_2004\bin
S:\Dsmp_Q4_2004\Dsmp_Reports\Telenor\adproof.exe DBUSER=a_user DBPSWD=a_pswd DBSTR=dbstr ADINFO=adinfo.lst TASKID=a_taskid
Here is the java code: in which i execute the batch file:
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("net use s: \\\\Dd-nt-fs\\DSMP15_FILES");
BufferedReader  b = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
while( (line=b.readLine())!=null) {
      System.out.println(line);
int exitVal = proc.waitFor();
System.out.println("Exit Value = "  + exitVal);
String[] cmd = new String[1];
cmd[0] = "C:\\Documents and Settings\\tikmi\\My Documents\\mysources\\DSMP Prototype\\print\\hallo3.bat";
// here i declared the needed settings of the environment variable and pass that array to the exec() method                   
String[] env = new String[8];
env[0] = "DSCFG=c:\\dscfg";
env[1] = "ORA_PATH=C:\\oracle\\ora92";
env[2] = "PSPATH=C:\\Documents and Settings\\tikmi\\My Documents\\mysources\\DSMP Prototype\\print";
env[3] = "ND_FONT=S:\\Dsmp_Q4_2004\\Fonts";
env[4] = "nxPS_FONT_DIR=%ND_FONT%";
env[5] = "PSFORMS=S:\\Dsmp_Q4_2004\\PsForms\\Telenor";
env[6] = "ND_PATH=S:\\Dsmp_Q4_2004\\resource";
env[7] = "PATH=S:\\Dsmp_Q4_2004\\Bin;%ORA_PATH%\\BIN;%ND_PATH%;%PATH%;";
rt  = Runtime.getRuntime();
proc = rt.exec(cmd, env);
b = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
while( (line=b.readLine())!=null) {
          System.out.println(line);
exitVal = proc.waitFor();
System.out.println("Exit Value = "  + exitVal);Maybe someone else had similar problems or can help me solving that problem.
Any advice would be very appreciated.
regards
mirkolino

finally I got it working now.
for those who are interested in the problem, my code that's now working is the following
Runtime rt = Runtime.getRuntime();
                        Process proc = null;
                        String cmd = "cmd.exe /c c:\\adproof\\hallo3.bat";
                        proc = rt.exec(cmd);
                        InputStream in = proc.getInputStream();
                        BufferedReader br = new BufferedReader ( new InputStreamReader(in));
                        String line;
                        while( (line=br.readLine()) != null) {
                            System.out.println(line);
                        int exit = proc.waitFor();
                        System.out.println();
                        System.out.println("Process exited with: " + exit);the problem was, that i have to handle and read the input stream
thanks for you help
greetings from mirkolino

Similar Messages

  • Passing schema name at runtime in batch file

    I am having a batch file where i am prompting users to tell the schema name to which they wish to connect at runtime. I am calling one .sql fil within that batch file to execute where i need user to connect to the specific schema at runtime
    My batch file looks like as
    set serveroutput on;
    set linesize 500;
    set scan on;
    spool test_bat.log
    Accept a PROMPT 'Enter the schema name you wish to connect: '
    Accept a_pw PROMPT 'Enter the password?: ' HIDE
    Accept a_connstr PROMPT 'Enter the connect string : '
    conn &a/&a_pw@&a_connstr
    Now after getting connected to the specified schema i would like to call some .sql file within the batch file which seems to be as
    select count(*) from <schema entered above>.table_name
    I want to use the above schema name (a) to get data from the tables.
    Please let me know how to get this.
    Thanks

    user11200661 wrote:
    That's fine but still i want to prefix the schema name within the .sql file. My .sql should contain the name of that parameter only as i want to get that parameter replaced by the schema name at runtime. Some other users are using the same .sql file and they have access to that specific schema only. i want to make the .sql file more general so that it can be used by everyone without altering it every time.Sorry, your requirement no longer makes sense.
    If people have to access a specific schema because they need the script for general use, then you will have to hard code the schema name into it.
    If the script is to prompt for the schema name and connect to that schema and then use that schema name inside the called sql script, then people would not be able to use it generically, as it would be reliant upon the schema name being passed in.
    It sounds as if you're trying to write one generic thing that needs to do two different tasks.
    Just have two scripts and make life simple.

  • Java Runtime.exec running java problem

    Hi, I have a simple server application, which I would like to run in the background. The following line works for me:
    Runtime.getRuntime().exec("cmd /c start java -jar ..\\server\\server.jar -Dlog4j.configuration=file:src\\test\\resources\\log4j.properties -filename src\\test\\resources\\server.properties");But it displays the cmd window and I am unable to destroy it. So I would like to use
    Runtime.getRuntime().exec("java -jar ..\\server\\server.jar -Dlog4j.configuration=file:src\\test\\resources\\log4j.properties -filename src\\test\\resources\\serverIntegration.properties");But it simply doesn't connect to the server. That means, it starts some java process in the background, but my client fails to communicate (i dont know whether the server doesnt respond or the client fails to send the message, but still, with the cmd /c start it works). So why is that?
    A related question. How do I end the process? It is a server that "doesn't end". So I have to kill it and I would assume, that running the java only command would be capable to be destroyed, but with the cmd I have no luck there. I have already tried full paths and the overload of exec with String[] params.

    Read [_When Runtime.exec() won't_|http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html].
    One reason why your server doesn't run is that it might be writing stuff to stdout (a.k.a System.out). And if your process doesn't read the newly created process' stdout, then that other process will block until something is read (which will be never).
    Read all of the pages of that article and follow its suggestions.

  • Batch File Problem????????????

    Dear All,
    I have created a batch file which will Export the Logical Oracle dump everyday of the week in their respective days folder eg. SUN, MON, TUE etc..... are the folders
    Now i am planning to put something like after taking Wednesdays backup the Mondays backup shuld be deleted automatically. I am confused how to set the Day-2 parameter in my bacth file. Below is my Batch file any suggestions wuld be of great help
    BATCH FILE:
    REM ########### Printing Date and Time ###########
    set backup_bin=C:\Schedules\Backup
    cd %backup_bin%
    echo "#######################################" >>%backup_bin%\backup.log
    echo "Backup process started" >>%backup_bin%\backup.log
    date /t >>%backup_bin%\backup.log
    time /t >>%backup_bin%\backup.log
    REM ########### set backup_folder variables ###########
    for /f "Tokens=1-4 Delims=/ " %%i in ('date /t') do set backup_day=%%i
    set backup_folder=D:\Oracle_DB_Tape_Backups\%backup_day%
    echo "backup folder is %backup_folder%" >>%backup_bin%\backup.log
    REM ########### Oracle Dump into D:\Oracle_DB_Tape_Backups\*** folders ###########
    echo "Oracle Dump process started" >>%backup_bin%\backup.log
    date /t >>%backup_bin%\backup.log
    time /t >>%backup_bin%\backup.log
    exp userid=apregs_admin/apregs_admin file='%backup_folder%\fulldump.DMP' log='%backup_folder%\log.log'
    date /t >>%backup_bin%\backup.log
    time /t >>%backup_bin%\backup.log
    echo "Oracle Dump process completed" >>%backup_bin%\backup.log
    REM ########### DELETE FROM PREV FOLDERS D:\Oracle_DB_Tape_Backups\*** folders ###########
    Regards

    If you want to handle this automatically, then you'll have to encode the weekday and perform arithmetics with the SET os command.
    I suggest you to use, rather, an S.O.S. (Script generated Out of SQL) You can handle the difficulties of dates directly in a sql script, then this script would generate the batch script, you would only schedule your sql script and it could generate the required os script.

  • Runtime.exec(bat file) : doesn't display stdio

    Hello, I need to start bat files from my Java Application
    to do this, I use
    Runtime.getRuntime().exec("my_bat.bat");
    a Dos console is opened.
    if my_bat.bat
    starts notepad.exe ==> it works
    if my_bat.bat
    does echo hello world ==> nothing is displayed.
    I would like the STDOUT procuded by the .bat file to be
    displayed in the console.
    Anyone can help me?
    Regards.

    You need to get the input stream from the process, and print out what it sends. Simply calling "waitFor()" will wait forever, since the stdout characters need to be read.
    Try this :
    InputStream st = Runtime.getRuntime().exec("hello_world.bat").getInputStream();
    int n;
    while ((n = st.read()) >= 0) {
      System.out((char)n);
    }Walter Gildersleeve
    Productivity Engineering, GmbH
    Freiburg, Germany

  • Any problem with Runtime.exec()

    I am required to launch a local exe from an applet. At present I am using AppletContext.showDocument().The problem with this is that in netscape a box is popped up forcing the user to save that exe file. The requirwment is to run it directly without any message being asked.
    A workaround is to use Runtime.exec(), it works, however I have heard that it is not platform independent.
    (1) Is there a better solution than Runtime.exec() ?
    (2) If not could you give me some info on Runtime.exec() and the problems associated with it ?
    (3) Is there a way to use AppletContext.showDocument() without the message being asked ?
    Shikari.

    First of all, Java is platform independent language, and has many security restriction in it's applets.
    so from an applet you can't excute a program using "Runtime.getRuntime().exec()".
    coz. there is security restriction on that.
    for the "AppletContext.showDocument()" this methid is for displaying the specified document on the client browser, so it can't excute a client program.
    if u need to use Runtime.getRuntime().exec() you have to get the client agreement for that.
    see the applet security restriction for more info.

  • Newbie problem with "Runtime exec" "OutputStream"

    I am running an external process (Oracle Sqlplus) from a simple GUI using "Runtime exec". My problem is that I'm only able to retrieve input from the process after the Java output stream is closed. If I don't close the output stream my application does nothing. As soon as I close the output stream the input from the external process is printed to the screen and the external process is killed.
    I want to be able to start the external process once and then send and receive multiple input and output streams to it without having to stop and restart the process. Currently the only way to retrieve input from the process is to close the Java output stream which closes the process.
    Is this possible? Am I doing something wrong?
    I am new to Java so I appreciate your help.
    My code is below. I am running it on Windows 2000 Workstation, Java 1.4.1, Oracle 8.1.7.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    class ProcessTest extends JFrame implements ActionListener {
        private JTextArea upperTextArea;
        private JTextArea lowerTextArea;
        private BufferedReader in;
        private BufferedWriter out;
        public ProcessTest() {
            initialiseComponents();
            setBounds(200, 200, 600, 400);
            setVisible(true);
        public void initialiseComponents() {
            Container contentP = getContentPane();
            contentP.setLayout(new BorderLayout());
            upperTextArea = new JTextArea("SELECT SYSDATE FROM DUAL;\n");
            lowerTextArea = new JTextArea();
            JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
                                                  new JScrollPane(upperTextArea),
                                                  new JScrollPane(lowerTextArea));
            splitPane.setDividerLocation(200);                                     
            JPanel buttonPanel = new JPanel();
            JButton runButton = new JButton("Start Process");
            runButton.addActionListener(this);
            JButton outputButton = new JButton("Write Output");
            outputButton.addActionListener(this);
            JButton flushButton = new JButton("Flush Output");
            flushButton.addActionListener(this);
            JButton closeOutputButton = new JButton("Close Output");
            closeOutputButton.addActionListener(this);
            JButton inputButton = new JButton("Read Input");
            inputButton.addActionListener(this);
            buttonPanel.add(runButton);
            buttonPanel.add(outputButton);
            buttonPanel.add(flushButton);
            buttonPanel.add(closeOutputButton);
            buttonPanel.add(inputButton);
            contentP.add(buttonPanel, BorderLayout.NORTH);
            contentP.add(splitPane, BorderLayout.CENTER);
        public void startProcess() {
            try {
                Process process = Runtime.getRuntime().exec("sqlplus -S " +
                                                             "scott/tiger");
                in = new BufferedReader(new InputStreamReader(
                                         process.getInputStream()));
                out = new BufferedWriter(new OutputStreamWriter(
                                          process.getOutputStream())); 
                System.out.println("Process Started.");                         
            catch(IOException e) {
                e.printStackTrace();
        public void writeOutput() {
            try {
                out.write(upperTextArea.getText().toCharArray());
                System.out.println("Output Write Completed.");
            catch (IOException e) {
                e.printStackTrace();
        public void flushOutput() {
            try {
                out.flush();
                System.out.println("Output Flush Completed.");
            catch (IOException e) {
                e.printStackTrace();
        public void closeOutput() {
            try {
                out.close();
                System.out.println("Output Close Completed.");
            catch (IOException e) {
                e.printStackTrace();
        public void readInput() {
            try {
                lowerTextArea.read(in, lowerTextArea);
                System.out.println("Input Read Completed.");
            catch (IOException e) {
                e.printStackTrace();
        public void actionPerformed(ActionEvent e) {
            String action = e.getActionCommand();
            if (action.equalsIgnoreCase("start process")) {
                Thread thread1 = new Thread(){
                    public void run(){
                        startProcess();
                thread1.start();
            else if (action.equalsIgnoreCase("write output")) {
                Thread thread2 = new Thread(){
                    public void run(){
                        writeOutput();
                thread2.start();
            else if (action.equalsIgnoreCase("flush output")) {
                Thread thread3 = new Thread(){
                    public void run(){
                        flushOutput();
                thread3.start();
            else if (action.equalsIgnoreCase("close output")) {
                Thread thread4 = new Thread(){
                    public void run(){
                        closeOutput();
                thread4.start();
            else if (action.equalsIgnoreCase("read input")) {
                Thread thread5 = new Thread(){
                    public void run(){
                    readInput();
                thread5.start();
        public static void main(String[] args) {
            new ProcessTest();
    }   

    At this point, I'm not getting the same results as you. I'm executing cmd.exe w/o args, and using the text area to do multiple directory listings in one go -- so far, the input thread has been able to keep up. Try copying & pasting the following below (I made a few changes to it). If it still doesn't work, it might help to know what operating system you're on, jdk version, etc..
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    class ProcessTest extends JFrame implements ActionListener {
        private BufferedReader in;
        private BufferedWriter out;
        private JTextArea upperTextArea;
        private JTextArea lowerTextArea;
        private ProcInThread pit;
        private class ProcInThread extends Thread {
            private BufferedReader in;
            private char[] cbuf = new char[8192];
            private int numRead;
            ProcInThread(BufferedReader in) {
                this.in = in;
            public void run() {
                Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
                do {
                    try {
                        numRead = in.read(cbuf, 0, cbuf.length);
                        if (numRead < 0) System.out.println("\n***END OF STREAM***\n"); // <-DEBUG CODE
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    SwingUtilities.invokeLater(new Runnable() {
                        public void run() {
                            lowerTextArea.append(new String(cbuf, 0, numRead));
                } while (numRead != -1);
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
        public ProcessTest() {
            initialiseComponents();
            setBounds(200, 200, 600, 400);
            setVisible(true);
        public void initialiseComponents() {
            Container contentP = getContentPane();
            contentP.setLayout(new BorderLayout());
            upperTextArea = new JTextArea("dir\ndir\ndir\ndir\ndir\ndir\ndir\n");
            lowerTextArea = new JTextArea();
            JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
                                                  new JScrollPane(upperTextArea),
                                                  new JScrollPane(lowerTextArea));
            splitPane.setDividerLocation(200);
            JPanel buttonPanel = new JPanel();
            JButton runButton = new JButton("Start Process");
            runButton.addActionListener(this);
            JButton outputButton = new JButton("Write Output");
            outputButton.addActionListener(this);
            JButton flushButton = new JButton("Flush Output");
            flushButton.addActionListener(this);
            JButton closeOutputButton = new JButton("Close Output");
            closeOutputButton.addActionListener(this);
            JButton inputButton = new JButton("Read Input");
            inputButton.addActionListener(this);
            buttonPanel.add(runButton);
            buttonPanel.add(outputButton);
            buttonPanel.add(flushButton);
            buttonPanel.add(closeOutputButton);
            buttonPanel.add(inputButton);
            contentP.add(buttonPanel, BorderLayout.NORTH);
            contentP.add(splitPane, BorderLayout.CENTER);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        public void startProcess() {
            try {
                Process process = Runtime.getRuntime().exec("cmd.exe");
                in = new BufferedReader(new InputStreamReader(
                                         process.getInputStream()),8192);
                out = new BufferedWriter(new OutputStreamWriter(
                                          process.getOutputStream()),8192);
                pit = new ProcInThread(in);
                pit.start();
                System.out.println("Process Started.");
            catch(IOException e) {
                e.printStackTrace();
        public void writeOutput() {
            try {
                out.write(upperTextArea.getText().toCharArray());
                System.out.println("Output Write Completed.");
            catch (IOException e) {
                e.printStackTrace();
        public void flushOutput() {
            try {
                out.flush();
                System.out.println("Output Flush Completed.");
            catch (IOException e) {
                e.printStackTrace();
        public void closeOutput() {
            try {
                out.close();
                System.out.println("Output Close Completed.");
            catch (IOException e) {
                e.printStackTrace();
        public void readInput() {
        public void actionPerformed(ActionEvent e) {
            String action = e.getActionCommand();
            if (action.equalsIgnoreCase("start process")) {
                Thread thread1 = new Thread(){
                    public void run(){
                        startProcess();
                thread1.start();
            else if (action.equalsIgnoreCase("write output")) {
                Thread thread2 = new Thread(){
                    public void run(){
                        writeOutput();
                thread2.start();
            else if (action.equalsIgnoreCase("flush output")) {
                Thread thread3 = new Thread(){
                    public void run(){
                        flushOutput();
                thread3.start();
            else if (action.equalsIgnoreCase("close output")) {
                Thread thread4 = new Thread(){
                    public void run(){
                        closeOutput();
                thread4.start();
            else if (action.equalsIgnoreCase("read input")) {
                Thread thread5 = new Thread(){
                    public void run(){
                    readInput();
                thread5.start();
        public static void main(String[] args) {
            new ProcessTest();
    }

  • Running batch file error

    I have already tried to find some solution on Java Essential forum, not much success there. I hope someone might suggest something here.
    Design: one big file, split into chunks, recombined according to some order, feeded to some exe file, and finally compilation of results.
    Problem: I can run that smoothly with jdk, however, when I use Java beans I am running into troubles. I can split the file, create an order, recombine the files, but when I try to feed it to an exe file(through a batch file) i get this error:
    endfile record was detected in a READ statement (UNIT = 3). Error occurs at _MAIN__. A dubplicate file name exists or the file cannot be foundThe main method is something like this:
            s.split_ftn07() ;
            s.Define_Order() ;
            for (int i = 1 ; i < 11 ; i ++)
                s.re_combine(i) ;
                s.run_Fastran(i) ;
            s.ass_Result() ;my batch file:
    @echo off
    cd
    "C:\JBoss\jboss-4.0.5.GA\bin\Fastran\FASTRAN.EXE"
    ren FTN04 FTN04i
    :finishand my method that runs the batch file: (as soon as it pass the exec(), it opens the cmd.exe windows and displays the error message).
    public void run_Fastran(int x)
           try
               File ftn07_i = new File("C:\\JBoss\\jboss-4.0.5.GA\\bin\\Fastran\\ftn07_" + x) ;
               File ftn07 = new File("C:\\JBoss\\jboss-4.0.5.GA\\bin\\Fastran\\ftn07") ;
               ftn07_i.renameTo(ftn07) ;
               String path = "";
               path = "cmd /c start C:\\JBoss\\jboss-4.0.5.GA\\bin\\Fastran\\FCall.bat";
               Runtime rt = Runtime.getRuntime();
               Process proc = rt.exec(path);
               String nameNew = "C:\\JBoss\\jboss-4.0.5.GA\\bin\\Fastran\\FTN04-" + x + "-p12";//change p12 with the crack path input by user.
               File file = new File("C:\\JBoss\\jboss-4.0.5.GA\\bin\\Fastran\\FTN04i");
               while (file.exists()==false)//until FTNO4i come into existence
                // File with new name
               File file2 = new File(nameNew);
                // Rename file
               file.renameTo(file2);
               File ftn07Back = new File("C:\\JBoss\\jboss-4.0.5.GA\\bin\\Fastran\\ftn07") ;
               File ftn07_iBack = new File("C:\\JBoss\\jboss-4.0.5.GA\\bin\\Fastran\\ftn07_" + x) ;
               ftn07Back.renameTo(ftn07_iBack) ;
               File ftn07_i_del = new File("C:\\JBoss\\jboss-4.0.5.GA\\bin\\Fastran\\ftn07_" + x) ;
               ftn07_i_del.delete() ;
           catch(Exception e)
               e.printStackTrace();
        }I am tired to figure out whats going on? Need some help here, will be greatly appreciated. Thanks

    Thanks to all, I really appreciate all the pains which all of you have taken in resolving my problem.
    It wasn't Java problem, rather batch file problem. I was only changing the directory, and was not providing for the exe file to run.
    @echo off
    cd  "C:\JBoss\jboss-4.0.5.GA\bin\Fastran"
    "C:\JBoss\jboss-4.0.5.GA\bin\Fastran\FASTRAN.EXE"
    ren FTN04 FTN04i
    EXIT
    :finishNow it is working fine.
    I did check the access permissions, no problem with that I guess. The problem was with the path. The batch file couldnt go pass bin directory, and I noticed that only today ;(. At any rate, I changed that and now it is all smooth and dandy.
    Once again, thanks a lot.

  • Performance issue Runtime. exec("cp folder1 folder") in Linux,Weblogic.

    Using Runtime. exec() copying files from folder1 to folder2 using cp command in Linux. It will take each file copy 2 sec if we use web logic 10.3 and jrocket. if we run in Linux without web logic it takes only 0.013 sec. why it takes more time to load cp command with web logic.
    Environment
    Weblogic 10.3
    Linux 5.2
    Jrocket 1.6

    A 64 bit VM is not necessarily faster than a 32 bit one. I remember at least on suggestion that it could be slower.
    Make sure you use the -server option.
    As a guess IBM isn't necessarily a slouch when it comes to Java. It might simply be that their VM was faster. Could have used a different dom library as well.
    Could be an environment problem of course.
    Profiling the application and the machine as well might provide information.

  • 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

  • Strange behavior when using Runtime.exec() to run batch file

    I've been struggling with this for hours.
    I have a Swing application which upon clicking a button, I want to execute a batch file. This batch file itself uses a command window.
    When I use
    Runtime load = Runtime.getRuntime();
    load.exec("cmd /c start c:\\renew\\renew2\\bin\\win\\renew.bat");
    The program (Renew) will start up no problem, but when I exit Renew, the command window stays put. I want the command window to close. Running Renew stand-alone, upon closing Renew, it will exit the command window.
    When I use
    Runtime load = Runtime.getRuntime();
    load.exec("cmd /c c:\\renew\\renew2\\bin\\win\\renew.bat");
    or
    Runtime load = Runtime.getRuntime();
    load.exec("c:\\renew\\renew2\\bin\\win\\renew.bat");
    When I press the button, sometimes the Renew application will come up right away, sometimes the Renew application will come up after a very long delay, and most times, the Renew application will only come up after I have closed the Swing frame where the button is located. When I use this code, the command window that Renew uses is never visible.
    What I want is to simply have the Renew application behave the same exact way launching from my Swing application as when Renew is being run standalone.
    Any suggestions? Thanks so much.
    Sincerely,
    Will

    Getting rid of start makes the startup time very variable. Sometimes it starts up right away, sometimes after many minutes, most times only after I close my application.
    Thanks, Any other suggestions?
    (BTW, I have read the famous "When Runtime.exec() won't" article, and have tried its suggestions to no avail)
    Message was edited by:
    willies777

  • Runtime.exec() and batch files

    I am having a problem on Windows 2000 while trying to execute a batch file with the Runtime.exec() method. Basically, the exit value returned from the call to Runtime.exec(), returned specifically by the waitFor() method in the Process class, is always zero, even if the batch file fails miserably. After looking into batch files further, it seems to me that the only way to get the exit value of the commands run in the batch file back to the Runtime.exec() call is to put "EXIT %ERRORLEVEL%" in the batch file. What this actually does is exit the command(cmd) shell that the batch file was running in with the exit code of the last command run. This is all great when calling the batch file with a Runtime.exec() call, but when you run it in a cmd window, the window closes when the batch file completes, because the call to EXIT exits the entire shell. I guess i'm just wondering, am i correct in assuming the exit value returned to the java process is going to be the exit value of the shell in which the batch file is running? I need to have the exit value actually indicate whether the batch file ran successfully or not, and if i have to put in the EXIT %ERRORLEVE% (which exits the cmd shell with the exit value of the last command run), then i'll do that, but if someone knows a better way of doing this, i am all ears. Thanks in advance

    To run any command from java code, the method is
    Runtime.getRuntime().exec( myCommandString )
    Where, myCommandString is something like "/full/pathname/command".
    If the pathname contains spaces (specifically in Windows), e.g. "c:\program files\windows\notepad", then enclose it in quotes within the quoted string. Or pre-tokenize them into elements of an array and call exec(String[] cmd) instead of exec(String cmd).
    From JDK1.3 there are two new overloaded Runtime.exec() methods. These allow you to specify starting directory for the child process.
    Note, there is a gotcha associated with reading output from commands. When the runtime exec's the process, it passes to it 3 streams, for stdin, stdout, and stderr; the out and err are buffered but the buffer size isn't very big. When your process runs, it reads (if needed) from in, and writes to out and err.
    If it doesn't write more than the buffer-size, it can run to completion.
    But if it tries to write more data to one or the other stream than the buffer can hold, the write blocks, and your process hangs, waiting for you to empty the buffer so it can write some more.
    So after the exec call, get the streams, and read from them in a loop until they both hit end-of-stream (don't block on either one, just read whatever is available from each, each loop iteration).
    Then when the streams have ended, call the process.waitFor() method to let it finish dying.
    Now, here is a code snippet how you achieve this.
    String strCommand = "cmd.exe /c " + strCommand;
    // For Solaris / unix it will be
    // String strCommand = "/usr/cobra/sol/runInstaller.sh";
    boolean bWait = true;
    //execute the command
    try
         Runtime r = Runtime.getRuntime();
         Process pr = r.exec(strCommand);
         Process pr = r.exec(callAndArgs);
         BufferedInputStream bis =new BufferedInputStream(pr.getInputStream ());
         int c=0;
         /** Outlet for IO for the process **/
         while (c!=-1)
              c=bis.read();
         /**Now wait for the process to get finished **/
         if(bWait == true)
              pr.waitFor();
              pr.destroy();
    catch(Exception e)
         System.out.println("Could not execute process " + strCommand);
         return(false);

  • Execute java class from a batch file called from runtime.exec

    Hi.
    I don´t know if this question fits here.
    I wan´t to execute a batch file (on Win XP) with runtime.exec. That batch file will execute another java program.
    I have the following code:
    Resolutor.java
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    public class Resolutor {
          * @param args
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              Runtime r = Runtime.getRuntime();
              //String[] command = { "cmd.exe", "/C",".\\lanzar.bat .\\ .\\ 001.res:001.dtt" };
              String[] command = { "cmd.exe", "/C",".\\tarea\\lanzar.bat " + args[0] + " " + args[1] + " " + args[2]};
              try {
                   //Process proceso = Runtime.getRuntime().exec("lanzar.bat");
                   Process proceso = Runtime.getRuntime().exec(command);
                   InputStream stderr = proceso.getErrorStream();
                InputStreamReader isr = new InputStreamReader(stderr);
                BufferedReader br = new BufferedReader(isr);
                String line = null;
                System.out.println("<ERROR>");
                while ( (line = br.readLine()) != null)
                    System.out.println(line);
                System.out.println("</ERROR>");
                   int exitVal = proceso.waitFor();
                   System.out.println("EXITVAL: " + exitVal);
              } catch (IOException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              } catch (InterruptedException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
    }lanzar.bat
    java Lanzador %1 %2 %3Lanzador.java
    import java.util.Vector;
    public class Lanzador {
          * @param args
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              Repetitiva rpt=new Repetitiva();
              String rutaFicheros=args[0];
              String rutaResultado=args[1];
              String[] ficheros=args[2].split(":");
              Vector<String> ficheroDatos=new Vector<String>();
              for(int i=0;i<ficheros.length;i++){
                   ficheroDatos.add(ficheros);
                   System.out.println(ficheros[i]);
              System.out.println("RUTA DE FICHEROS: " + rutaFicheros);
              System.out.println("RUTA DE RESULTADOS: " + rutaResultado);
              System.out.println("CALCULAR");
              rpt.setRepetitiva(ficheroDatos, rutaFicheros, rutaResultado);
              rpt.calcular();
    }I´ve got Resolutor.class in /res and the other two files (and the rest of the files for running) in /res/tarea.
    If I execute /res/tarea/lanzar.bat from the command line everything works fine, it calls java and runs lanzador without problem.
    The problem comes when I try to execute the batch file via Resolutor.class. It executes the batch file without problem, but it throws a *java.lang.NoClassDefFoundError: Lanzador* when launching the new java application.
    Any ideas of how can I solve that problem. (It must do it via batch file).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    Well, I tried putting in the bat file java -classpath .\tarea Lanzador %1 %2 %3 and didn´t work.
    I ve tried the bat modification, and the directory in x.txt is k:\res instead of k:\res\tarea.
    I´ve tried to modifiy it to java .\tarea\Lanzador and didn´t work so I have put a cd like the following and it appears to work.
    cd tarea
    java Lanzador %1 %2 %3Thanks for the replies.

  • Runtime.exec--problems writing to external file

    Hi. I went to http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html, and am still quite confused regarding the use of Runtime.exec, for my purposes. I want to decompile a CLASS file using javap, and then write that to a TXT file, for easier reading/input to JAVA. Now, I use the following code (a modification of what I got from http://www.mountainstorm.com/publications/javazine.html, as the "traps" article's sample code is WAY too confusing--they say the compiler had the output sent to text.txt, without even showing how in the source code they did that), but it hangs up. Modifications to the string array cause different results, such as showing the javap help menu, or saying that the class wasn't found, but I think the way I did the array here is right:
    import java.util.*;
    import java.io.*;
    public class Test {
            try {
             String ls_str;
                String[] cmd = {"C:\\j2sdk1.4.2_04\\bin\\javap", "-c", "-classpath", "H:\\Java\\metricTest", "metricTest > blah.txt", ""};
                Process ls_proc = Runtime.getRuntime().exec(cmd);
             // get its output (your input) stream
             DataInputStream ls_in = new DataInputStream(
                                              ls_proc.getInputStream());
             try {
              while ((ls_str = ls_in.readLine()) != null) {
                  System.out.println(ls_str);
             } catch (IOException e) {
              System.exit(0);
         } catch (IOException e1) {
             System.err.println(e1);
             System.exit(1);
         System.exit(0);
    }

    Also, jesie, I realize that's what I need...the only
    problem is, the name "test.txt" is nowhere to be found
    in the source code! lolLooks like I have to explain this, then.
    When you look at a Java program you'll notice that it always has a "main" method whose signature looks like this:public static void main(String[] args)When you execute that program from the command line, it takes whatever strings you put after the class name and passes them to the main program as that array of strings. For example if you run it likejava UselessProgram foo bar hippothen the "java" command takes the three strings "foo", "bar", and "hippo" and puts them into that args[] array before calling the "main" method.
    That means that inside the "main" method in this case, "args[0]" contains "foo", "args[1]" contains "bar", and "args[2]" contains "hippo".
    Now go back to the example and see how it lines up with that.

  • 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

Maybe you are looking for