Runtime.exec ignores the working directory argument

Hi Folks,
I need to run a batch file in a particular directory, from a Java program.
Here, I want to run "startMySQL.bat" from the ./bin directory.
I used the following code to do so.
     String commandToExecute = "startMySQL.bat";
     File file = new File("bin");
Process sqlPrcs = Runtime.getRuntime().exec(commandToExecute, null, file);     
When I run these lines in a program, I get the following exception:
java.io.IOException: CreateProcess: startMySQL.bat error=2
at java.lang.Win32Process.create(Native Method)
at java.lang.Win32Process.<init>(Unknown Source)
at java.lang.Runtime.execInternal(Native Method)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at com.aperto.ems.packetmax.AuthenticationScreen.startDB(AuthenticationScreen.java:603)
at com.aperto.ems.packetmax.AuthenticationScreen.validateUserAndReinitialize(AuthenticationScreen.java:479)
at com.aperto.ems.packetmax.AuthenticationScreen.access$0(AuthenticationScreen.java:468)
at com.aperto.ems.packetmax.AuthenticationScreen$OnOKButtonPress.actionPerformed(AuthenticationScreen.java:628)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$ForwardActionEvents.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener$ReleasedAction.actionPerformed(Unknown Source)
at javax.swing.SwingUtilities.notifyAction(Unknown Source)
at javax.swing.JComponent.processKeyBinding(Unknown Source)
at javax.swing.JComponent.processKeyBindings(Unknown Source)
at javax.swing.JComponent.processKeyEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.KeyboardFocusManager.redispatchEvent(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.dispatchEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
"error=2" in Windows mean "not able to find the file".
Any clues on how I can run the batch file from a particular working directory?
Thanks!

Hi,
I changed the code to print the user.dir output and the absolute path of the file. It looks like this:
String commandToExecute = "startMySQL.bat";
File fl = new File("bin");
System.out.println(fl.getAbsolutePath());
System.out.println(System.getProperty("user.dir"));
Process sqlPrcs = Runtime.getRuntime().exec(commandToExecute, null, fl);
Below is the output I get:
C:\Program Files\Aperto\WaveCenter\Back-End_Server_2.0_build8\bin
C:\Program Files\Aperto\WaveCenter\Back-End_Server_2.0_build8
java.io.IOException: CreateProcess: startMySQL.bat error=2
at java.lang.Win32Process.create(Native Method)
at java.lang.Win32Process.<init>(Unknown Source)
at java.lang.Runtime.execInternal(Native Method)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at com.aperto.ems.packetmax.AuthenticationScreen.startDB(AuthenticationScreen.java:604)
at com.aperto.ems.packetmax.AuthenticationScreen.validateUserAndReinitialize(AuthenticationScreen.java:479)
at com.aperto.ems.packetmax.AuthenticationScreen.access$0(AuthenticationScreen.java:468)
at com.aperto.ems.packetmax.AuthenticationScreen$OnOKButtonPress.actionPerformed(AuthenticationScreen.java:629)
I assure you, "startMySQL.bat" is there under "bin"
Thanks,
Sandeep

Similar Messages

  • How to set the working directory for reports in linux

    Hi All,
    Can you anyone help me to set the working directory for oracle application server 10g reports? I am using RHEL4 and AS10g. Actually i want to run my reports from my define
    working directory. How can I do this?
    Thanks in advance
    Arif

    Hi,
    your rep_srv.conf should look like something like
    +<?xml version = '1.0' encoding = 'ISO-8859-1'?>+
    +<!DOCTYPE server PUBLIC "-//Oracle Corp.//DTD Reports Server Configuration //EN" "file:D:\oracle\FRHome_1/reports/dtd/rwserverconf.dtd">+
    +<server version="10.1.2.0.2">+
    +<!--Please do not change the id for reports engine.-->+
    +<!--The class specifies below is subclass of _EngineClassImplBase and implements EngineInterface.-->+
    +<cache class="oracle.reports.cache.RWCache">+
    +<property name="cacheSize" value="50"/>+
    +<!--property name="cacheDir" value="your cache directory"-->+
    +<!--property name="maxCacheFileNumber" value="max number of cache files"-->+
    +<!--property name="ignoreParameters" value="parameter names to be ignored in constructing cache key, separated by comma ','"-->+
    +</cache>+
    +<engine id="rwEng" class="oracle.reports.engine.EngineImpl" initEngine="1" maxEngine="3" minEngine="0" engLife="50" maxIdle="30" callbackTimeOut="90000" jvmOptions="-Xmx512M -Xss512K">+
    +<!--property name="sourceDir" value="your reports source directory"/-->+
    +<!--property name="tempDir" value="your reports temp directory"/-->+
    +<!--property name="keepConnection" value="yes"/-->+
    +</engine>+
    +...+
    some more definitions
    +..+
    +<!--pluginParam name="proxy" type="file">proxyinfo.xml</pluginParam-->+
    +<pluginParam name="xmlpds" type="file">xmlpds.conf</pluginParam>+
    +<pluginParam name="jdbcpds" type="file">jdbcpds.conf</pluginParam>+
    +<pluginParam name="textpds" type="file">textpds.conf</pluginParam>+
    *<environment id="APP1">*
    *+<envVariable name="REPORTS_PATH" value="/application1/reports"/>+*
    *+</environment>+*
    *+<environment id="APP2">+*
    *+<envVariable name="REPORTS_PATH" value="/application2/reports"/>+*
    +</environment>+
    +</server>+
    The environment ids you can choose yourself and you have to put them in there yourself too (here I put two environments for two different applications "1" and "2").
    If you call a report from Forms, then you have to code something like
    ADD_PARAMETER(p_list,'ENVID',TEXT_PARAMETER,'APP1');
    Details depend on how you call your reports, my example is for using a parameter list and calling a report out of application1
    Hope that helps.
    Volker

  • How can I get the working directory of a project from an Annotation Processor in Java

    I am writing an annotation processor in Java and in this annotation processor I want to be able to find a file in the Project hierarchy of the project on which I am using this annotation processor. Through the annotation I can pass in the path of the file I am searching for relative to the project root but i cannot retrieve the project's working directory.
    Let's say that the processor is MyCustomProcessor and I am using it on the project MyProject. I want to be able to access(read) a file (a properties file) from the project structure of MyProject from the "process" method of MyCustomProcessor.
    I have read this link Eclipse - Annotation processor, get project path but when I use their solution I get a null returned from the StandardJavaFileManager.getLocation(StandardLocation.SOURCE_PATH) call.
    Some more details regarding the implementation:
    MyAnnotationProcessor:
    @SupportedAnnotationTypes(value = {"MyAnnotation" })
    @SupportedSourceVersion(RELEASE_6)
    public class MyCustomProcessor extends AbstractProcessor {
    @Override public boolean process(final Set<? extends TypeElement> annotations, final RoundEnvironment roundEnv) {
    for (final Element element : roundEnv.getElementsAnnotatedWith(MyAnnotation.class)) {
    <!-- Here is where I would like to get the working directory !-->
    More details about the testing and development environment: Eclipse Kepler, JRE 1.7.
    If you need more details just ask.

    There is an identical post with an answer located at this link.

  • [Solved] a.out not recognizing the working directory

    It's a little bit embarrassing because this issue doesn't seem terribly complicated, but I'm having trouble with executing the a.out file (Hello World) that gcc produces. I have to explicitly state the directory that a.out is in to run it, even though it's in the working directory. Other programs, such as Nano, recognize the working directory just fine and it is able to open files inside the working directory without having me explicitly state the full directory name.
    Any help would be greatly appreciated.
    Last edited by bananaman (2011-03-23 03:16:10)

    The easiest and most secure way would be using the relative path to the executable:
    ./a.out
    If you use a single directory for writing/testing your programs, you could add it to your user PATH. Not a major security risk, but if you do so, be careful what executables are in the dir.
    ~/.bashrc (or ~/.bash_profile):
    [[ -d ~/cpp ]] && export PATH="$PATH:~/cpp"
    Adding the current working directory to PATH is a security risk, so I wouldn't recommend it.
    Last edited by sisco311 (2011-03-23 03:12:29)

  • Periodic Message: You have some checked-out files in the working directory

    Hi,
    we are recieving a periodic message (appearing every 5 minutes) saying:
    "You have some checked-out files in the working directory. We recommend that you check in the files after editing. Click here to checkin the files.
    After clicking on the message easyDMS is opened and Private- & Public-Folder are shown.
    There are no checked out files on the client.
    What happened?
    Thanks a lot!
    Edited by: B Lobascio on Feb 8, 2011 5:13 PM

    After changing the Working directory in easyDMS preferences the message did not apear anymore.
    That means that there have been some some damaged documents in origin working directory.
    Edited by: B Lobascio on Feb 16, 2011 10:35 AM

  • Runtime.exec() does not work normally

    I try to wrapper the oracle connect command on unix using this function:
    runtime.exec("sqlplus username/password@dbinstance")
    it is ok on windows, but on unix, after runing the class, I get nothing. what is the problem?
    Please help me. thanks

    There are several traps with runtime.exec(). The most important one is that you should read
    the output stream of the launched program. Otherwise it will stop running when the console buffer overflows. The size of the buffer differs for various OSes.
    Look at this article:
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
    It it does not answer your problem, try to search the forums:
    http://search.java.sun.com/Search/java?qt=%2B%22exec%22+-%22Replies%3A+0%22&col=javafrm&rf=0&qp=%2Bforum%3A31
    This problem has been asked hundreds of times.
    Hope, this helps.

  • Runtime.exec() does not work under Linux

    Hi,
    I have a generic application runner class that runs an external
    program and redirects stdout/stderr to a buffer/file.
    While everythings works just fine under Windows, I get the
    following exception under Linux trying to run the Java interpreter
    'java':
    java.io.IOException: "/usr/lib/SunJava2-1.3.1/jre/bin/java": not found
    at java.lang.UNIXProcess.forkAndExec(Native Method)
    at java.lang.UNIXProcess.<init>(UNIXProcess.java:139)
    at java.lang.Runtime.execInternal(Native Method)
    at java.lang.Runtime.exec(Runtime.java:546)
    at java.lang.Runtime.exec(Runtime.java:413)
    I have checked that the file /usr/lib/SunJava2-1.3.1/jre/bin/java
    exists.
    Any help appreciated!
    Marc

    can I ask how you solved it? I am having a problem
    with quotes just now to and it might help me!I simply tested what the current platform is and
    only used quotes under Windows.
    Marc

  • Runtime.exec() does not work?

    I'm trying to invoke a C++ executable from java using the Runtime.exec() method. The C++ application accepts a filename as a command line argument & opens the file. This C++ app is unicode enabled i.e. it can accept UTF-16 (wide char) parameters. Howevere, when i invoke this application using Java's Runtime.exec() and specify a japanese file name as an argument, the japanese characters get converted to '?' characters by the time they are received in the C++ application. I'm running this application on Windows 2K, default i.e. English version.
    Looking at the source code of Runtime class, it seems that the exec()
    function makes use of a native helper function - execInternal(). Does
    this function support the entire unicode range?
    Is there any way we can avoid the conversion of japanese characters to '?' characters? Also, is there any other alternative for invoking an external application with Unicode (Say, japanese) arguments?
    Please reply ASAP.
    Thanks!

    >
    I'm trying to invoke a C++ executable from java using
    the Runtime.exec() method. The C++ application accepts
    a filename as a command line argument & opens the
    file. This C++ app is unicode enabled i.e. it can
    accept UTF-16 (wide char) parameters. Howevere, when i
    invoke this application using Java's Runtime.exec()
    and specify a japanese file name as an argument, the
    japanese characters get converted to '?' characters by
    the time they are received in the C++ application. I'm
    running this application on Windows 2K, default i.e.
    English version.
    Looking at the source code of Runtime class, it seems
    that the exec()
    function makes use of a native helper function -
    execInternal(). Does
    this function support the entire unicode range?I don't know because I've never tested this case specifically.
    You didn't show your code though. How are you reading in the String? You mentioned that you passed a Japanese character String as a filename argument. I also read that you are running on an English Win2K platform. How did you read that argument in? It may just be that you read the argument in your default encoding(English) and you needed to specify an alternate one.

  • Runtime.exec does not work for commands with lengthy outputs

    I need to use Runtime.exec to run some custom commands on a Unix box. I have been doing this for quite some time now and had begun to feel comfortable when recently I started facing a problem. The thing is, whenever there is a command which prints a lot of data on to the console, the program is not able to exit from the waitFor method. Is there some thing that can be done about this?
    Following is a part of the code I use:
    Runtime rt = Runtime.getRuntime();
    Process p = rt.exec (command);
    System.out.println ("Got the process");
    int exitValue = p.waitFor();
    System.out.println ("Exit value: " + exitValue);When the output of the "command" is lengthy, it hangs after printing "Got the process".
    PS: By lengthy output, I mean that the command results in printing lines to the console which might be more than 100 in number. Say, something like what "ls -R /" would do in Unix / Linux.

    From java.lang.Process API doc:
    The Runtime.exec methods may not work well for special processes on certain native platforms, such as native windowing processes, daemon processes, Win16/DOS processes on Microsoft Windows, or shell scripts. The created subprocess does not have its own terminal or console. All its standard io (i.e. stdin, stdout, stderr) operations will be redirected to the parent process through three streams (Process.getOutputStream(), Process.getInputStream(), Process.getErrorStream()). The parent process uses these streams to feed input to and get output from the subprocess. Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock.
    So you need to consume the process' output. Check the StreamGobbler example from this article.
    Hope it helps.

  • Runtim exec() method not working.....giving Exception

    whts the code to use exec() method. i m using it as follows and also catching exception.
    Runtime r=Runtime.getRuntime();
    Process p=r.exec("java A");
    code is giving IOException at runtime with error=2.

    Here is an example I used when I first needed to test the runtime.exec
    import java.util.*;
    import java.lang.*;
    import java.io.*;
    public class TestRuntime {
        public static void main(String args[])
            try
                Runtime rt = Runtime.getRuntime();
                Process proc = rt.exec("java A");
                InputStream stderr = proc.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 = proc.waitFor();
                System.out.println("Process exitValue: " + exitVal);
            } catch (Throwable t)
                t.printStackTrace();
    }Are you waiting for the process to end before exiting your program?

  • Making jar file in folder other than the working directory

    Hello!
    I am trying to make jar files by using a program. I execute jar commands at runtime. The problem is that when a command is given like this
    jar cvmf C:\HTTPS\Manifest.txt C:\HTTPS\khalid.jar C:\HTTPS\client.cer
    C:\HTTPS\Client.jar C:\HTTPS\client.keys C:\HTTPS\HelloRunnableWorld.class C:\HT
    TPS\HelloRunnableWorld.java C:\HTTPS\keytool interaction commands.txt C:\HTTPS\M
    akeJarRunnable.class C:\HTTPS\MakeJarRunnable.java C:\HTTPS\MakeJarRunnable.zip
    C:\HTTPS\Manifest.txt C:\HTTPS\myjar.jar C:\HTTPS\myjar_r.jar C:\HTTPS\Problem s
    cenario.txt C:\HTTPS\Run.bat C:\HTTPS\scompressed.jar C:\HTTPS\Security.jar C:\H
    TTPS\Server.jar C:\HTTPS\server.keys C:\HTTPS\serverexport.cer C:\HTTPS\Starter.
    class C:\HTTPS\Starter.java C:\HTTPS\Umer Farooq - What I did.ppt C:\HTTPS\Umer.jar
    The jar file is created but it has 0 bytes in it. No data is written into it, despite all the files being there.
    Thank You

    That is not the way to create jar files. Here is how you do it.
    Under say c:\ create directory "utils".
    Copy all of the *.java" files which will be part of this jar file "utils.jar". After moving files into c:\utils , make sure every single file has the first line of code as "package utils;" (without the quotes though)
    Type in "javac *.java" to compile all of the files at once.
    cd over to the parent directory and then type in
    jar cvf utils.jar c:\utils\*.class
    This will create utils.jar file under c:\

  • Runtime.exec - hidding the ugly black dos window

    Hello,
    Could someone tlle me how to hide the dos command which is always opened when using Runtime.exec on a windows OS?
    I also know that there's already lots of questions already posted on this subject but I can't find them.. So links could help me....
    Loic

    Here's what came up when I searched the forum using "hide runtime":
    http://search.java.sun.com/Search/java?col=javafrm&qp=%2Bforum%3A31&qt=hide+runtime&x=10&y=10

  • Runtime.exec() - Strips the parameter list on encountering  a newline(\n)

    I am executing a batch file from Runtime.exec() and i am passing a list of parameters to the batch file in the form of name=value pairs.One of the parameters value is a multiline text containing "\n" characters.i.e input from a textarea.
    When my program executes the batch file it prints all the parameters till it encounters the "\n" character and strips all the remianing parameters.And it does not show any error .
    Is this a bug of Runtime.exec method ?
    If not, how to resolve this problem?

    Bug in Runtime.exec? Nope, it's probably you and your code.
    Read this - everyone who uses Runtime.exec should:
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html

  • Configuring the working directory

    Hi all,
    I am fairly new with JSP. I am currently creating all my JSP files under TOMCAT_HOME/webapps/ROOT/myDirectory. But I would like to work outside the TOMCAT_HOME directory, for example c:/myDirectory.
    Has anyone considered doing this and if yes, how can i make this configurations.
    Thanks.

    in the conf/server.xml file:
    <Context path="/myDirectory" docBase="c:/myDirectory" reloadable="true" debug="0">
    </Context>
    path is the webapp name in the url (http://localhost:8080/myDirectory)
    docbase is the directory where the code is placed. Not sure about the slash or whether it should be a back slash.

  • Runtime exec() Problem, change working dir

    Hi!
    I have following problem:
    I want to call an executable from my home-directory under Linux this way:
    Runtime rt = Runtime.getRuntime();
    Process pr = rt.exec("/home/tom/prog/exec-command");
    Unfortunately I'm getting either exception "file not found" (but it's there) or no complain but no program run...
    perhaps something's wrong with the path-name?
    If I call the program in the directory with a shell it works fine.
    Would be very happy if anybody can give a hint!
    Thanks a lot,
    Manuel

    You are interested in the programs output? Does it write to stdout or stderr or both? In any case, my advice is to go multithreading and use one thread to wait for the program to exit, one to read stdout and one to read stderr. If you just use one thread for reading, the program might block. I normally use something like this:
      final int BUFFER = 2048;
      final Process p = Runtime.getRuntime().exec(args);
      //read standard out output of the external executable
      //in seperate thread to avoid I/O deadlocks
      new Thread()
        public void run()
           try
             BufferedInputStream in =  new BufferedInputStream (p.getInputStream());
             int i;
             byte[] buf = new byte[BUFFER];
             while ( (i = in.read(buf, 0, BUFFER)) != -1 )
                System.out.write(buf, 0, i);
             in.close();
           catch (IOException e)
             e.printStackTrace();
      }.start();
      //read standard error output of the external executable
      //in seperate thread for symmetry
      new Thread()
        public void run()
           try
             BufferedInputStream in =  new BufferedInputStream (p.getErrorStream());
             int i;
             byte[] buf = new byte[BUFFER];
             while ( (i = in.read(buf, 0, BUFFER)) != -1 )
                System.err.write(buf, 0, i);
             in.close();
           catch (IOException e)
             e.printStackTrace();
      }.start();
      //Wait for the external process to finish     
      int exitCode = p.waitFor();          
      if ( exitCode != 0 )
        throw new IOException("Executable stopped with error code "+exitCode); Cheers, HJK

Maybe you are looking for