Runtime.exec() with .bat-files in a jar

Hi All,
I've written a java-Program, which calls .bat-files per Runtime.exec() for some OS-specific tasks.
Everything works fine, but if I want to pack the whole code and the .bat-files into several jars, I can't get the bat-files to run. I have tried to get it to work with "getClass().getResource()" as I do the same for my Images, and the returned URL seems to be OK so far (something like jar:file:/c:/test.jar! testpkg/test.bat). I converted this URL into a String and tried to run Runtime.exec() with it, but I always get a Runtime-Exception.
The String looks exactly like the URL, when I print them to console.
These bat-files are essential for the application and I would not try to pack them into a jar if I hadn't to distribute this application as a signed applet to unknown users, too.
I hope there is anyone out there who can tell me if and how it is possible to run an external program out of java, which is packed into a jar, so thanx in advance to any helpful replies.
acdeka

You can't run the .bats simply because the shell can't access it. You tell it to run a file that simply doesn't exist in the OS.

Similar Messages

  • Runtime.exec() with language specific chars (umlauts)

    Hello,
    my problem is as follows:
    I need to run the glimpse search engine from a java application on solaris using JRE 1.3.1 with a search pattern containing special characters.
    Glimpse has indexed UTF8 coded XML files that can contain text with language specific characters in different languages (i.e. german umlauts, spanish, chinese). The following code works fine on windows and with JRE 1.2.2 on solaris too:
    String sSearchedFreeText = "Tür";
    String sEncoding = "UTF8";
    // Convert UTF8 search free text
    ByteArrayOutputStream osByteArray = new ByteArrayOutputStream();
    Writer w = new OutputStreamWriter(osByteArray, sEncoding);
    w.write(sSearchedFreeText);
    w.close();
    // Generate process
    String commandString = "glimpse -y -l -i -H /data/glimpseindex -W -L 20 {" + osByteArray.toString() + "}";
    Process p = Runtime.getRuntime().exec(commandString);
    One of the XML files contains:
    <group topic="service-num">
    <entry name="id">7059</entry>
    <entry name="name">T&#195;&#188;rverkleidung</entry>
    </group>
    Running the java code with JRE 1.2.2 on solaris i get following correct commandline
    glimpse -y -l -i -H /data/glimpseindex -W -L 20 {T&#195;&#188;rverkleidung}
    --> glimpse finds correct filenames
    Running it with JRE 1.3.1 i get following incorrect commandline
    glimpse -y -l -i -H /data/glimpseindex -W -L 20 {T??rverkleidung}
    --> glimpse finds nothing
    JRE 1.2.2 uses as default charset ISO-8859-1 but JRE 1.3.1 uses ASCII on solaris.
    Is it possible to change the default charset for the JVM in solaris environment?
    Or is there a way to force encoding used by Runtime.exec() with java code?
    Thanks in advance for any hints.
    Karsten

    osByteArray.toString()Yes, there's a way to force the encoding. You provide it as a parameter to the toString() method.

  • Runtime.exec() ... executing a java jar from within an NT command file

    Hello,
    I spent the better part of yesterday seeking insight to this with little success. So I hope someone here can direct me in a productive direction.
    I set-up my runtime.exec in a manner similar to the article on javaworld.com which is often referred to here, with two threads to empty the output and error streams of the NT command file I am executing.
    The command file works perfectly from the command line.
    I am currently attempting to build a gui which will automate regression testing for another application. This requires third party software to be running prior to the execution of the test suite. This third party software is started using an NT command file. The command file sets up an environment (classpath, server flags, etc.) and then executes a jar file. When this command file is run from my Gui, the output is identical to the command being run from the command line. Then when the jar file is to be executed, the command file output shows a "file not found" error, but only when executed from my Gui.
    My call to runtime exec looks like this.
    cmdString = new String("commandtoexecute");
    fileLoc = new String("Fully qualified path to command file");
    String [] envp = new String[0];
    testProcess = Runtime.getRuntime().exec(cmdString, envp, fileLoc);
    // some code to process the output streams of testProcess
    Other Info:
    Gui currently executed within Eclipse IDE
    BEA WebLogic is the third party software

    First, my app has the requirement of allowing the user to start WebLogic if it is not already running.Unfortunately, I can't change the requirement.
    But I would say that in a production environment WebLogic should always be running.
    I guess it's an assumption that I'd make a priori. You're jumping through too many hoops to accomplish something that is better solved with a phone call to the server admin: "Please start the WebLogic service."
    .... Side question ... any recommendations on detecting if it is already running? grin
    Yes, call the server admin and ask why you can't have 99.999% availability of a critical resource.
    Second, development is on a hardened system (i.e. very
    long time getting approval for additional software on
    the system).Cactus and JUnit are both open source. No fees involved. If you can install a JAR, you can use these tools.
    Better yet, you can drive them automatically as part of your Ant build process. A GUI implies a person in front of it to start and monitor the tests. JUnit and Ant are all about automating these things so they're run every time you rebuild and redeploy the code. You get XML reports on test results that are displayable in a browser. You can even e-mail the test summary to all developers so they can see if a test broke the build. If a test breaks, you don't deploy. That's the way to go, IMO.
    When you have a working Ant build.xml, the next step is to automate the build completely using a tool like ThoughtWorks' CruiseControl.
    Thank you for you suggestions though. I will read up on Cactus to see if it could help me here.You're welcome. Good luck. Sorry that I'm not more help.

  • UNIX Problem with method Runtime exec(String[],String[],File)

    Hello !!
    i'm french
    scuse my english
    I got a probleme with method exec(String[],String[],File) of Runtime Class
    i don't have any probleme when my program runs on Windows NT but the same program on UNIX doesnt execute my command..
    When i use exec(String[]) methode i dont have this problem ...but i need the second one methode because i have to execute my command in a different directory than the JAVA program.
    I need that results of this command are placed in this drectory so that i can't use an exex() like that :
    exemple with a perl :
    "perl /toto/titi/hello.pl"
    I want to execute this :
    "perl hello.pl" (and hello.pl is placed in /toto/titi)
    Conclusion :
    the exec(String[],String[],File) solution is ok with NT ...
    but with UNIX ????
    Is there other solution ??
    Should i do a "cd" command before my execution ? how can i do this ??
    Thanks !!!!

    Could you post your source code (only relevant part)
    Raghu

  • 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);

  • Runtime.exec() with japanese arguments?

    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 have a very similar problem. I am invoking cvs through Runtime.exec, and I am using it to add and check in files with chinese characters in the name, and it is failing with the following cvs error:
    Could not add resource file &#32435;&#20986; in directory C:\test to repository: cvs add: nothing known about ??
    The error message comes from cvs, and I have been able to track it down to the call string I pass to exec. It is correct when passed in but the command fails. For laughs I tried to call something simpler, like mkdir:
    err mkdir ?? is: The filename, directory name, or volume label syntax is incorrect.
    It seems pretty clear to me that although the callstring is correct, the call to exec fails, and the special characters are replaced with questionmarks, which seems to me to be an encoding issue.
    Did you get any solution to your problem, or does anyoen else have an answer for this?

  • Runtime.exec with spaces not working EVEN using String[]!!

    Hi everyone,
    I need to start the rmi registry from some code,and i need to pass it the classpath of two jars when initialising it. My problem is that the paths I set aren't taken when they contain a space.
    Here's the code:
    <code>
    String rmiRegistryCommandLine[] = new String[] {
    + System.getProperty("java.home")
    + "\\bin\\rmiregistry.exe\"",
    "-J-Djava.class.path=\""+System.getProperty("user.dir")+"\\MyJar.jar\"",
    "1099"};
                                            Runtime.getRuntime().exec(rmiRegistryCommandLine);
    </code>
    I know that Runtime.exec(String) tokenizes the input, which is why I'm not using it, but Runtime.exec(String[]) isn't supposed to tokenize the input. System.getProperty("user.dir") can contain a space, so I put quotes around that, but I need the -J-Djava.class.path in the same string. I tried breaking it up into two more separate strings but it didn't even run for normal non-space paths then. I am sure that if the whole -J-Dblah....upto MyJar.jar was in quotes then it would work, but I need the classpath in quotes separately as it could contain a space.
    Can anyone help me get this working?

    Ya, that's fine but the command line I want to pass is:
    d:\j2sdk1.4.0\bin\rmiregistry.exe -J-Djava.class.path=d:\my dir with spaces\MyJar.jar;d:\my more dir with spaces\MyJar2.jar 1099
    If I say
    arg[0]="d:\\j2sdk1.4.0\\bin\rmiregistry.exe";, that's finebut arg[1] is the problem
    if I say
    arg[1]="-J-Djava.class.path=d:\\my dir with spaces\MyJar.jar; d:\\my more dir with spaces\\MyJar2.jar";, then it definitely won't work on 9X machines and probably not on NT.
    if I break up arg[1] into:
    arg[1]="-J-Djava.class.path=";
    arg[2]="d:\\my dir with spaces\\MyJar.jar";
    arg[3]=";";
    arg[4]="d:\\my more dir with spaces\\MyJar2.jar";I'll need to put quotes around the two individual two class paths or else it won't work.
    I find though that if I put the classpath as follows
    d:\"my dir with spaces"\MyJar.jar then it seems to work.
    I think a regular expression function to search for any directory with spacees and then put quotes around it and reinsert it into the path would be the solution.

  • Can not run business rule with bat file

    Hi all,
    I've problem with using *.bat file to run business rule. My Essbase version is 11.1.1.3 and the syntax within
    *.bat is simple, but I always got the Usage message and can not execute the rule.
    The error result as blow(I already execute the syntax in command panel directly):
    C:\Hyperion\products\Essbase\eas\console\bin>CmdLnLauncher -SWILSON -Usynadmin -P111111 -r0004_COPYDATA
    Usage: CmdLineLauncher [-p:<passwordFile>] -Sservername -Uusername [-rBusiness R
    ule Name | -sSequence Name] [-fRun Time Prompts file] [-validate]
    My *.bat file content as below:
    cd c:\Hyperion\products\Essbase\eas\console\bin
    call CmdLnLauncher -SWILSON -Usynadmin -P1111111 -r0004_COPYDATA
    Is there something wrong? If anyone know about this problem, please help,thanks!!

    Hi,
    Here is a brief overview on how to use the command line launcher.
    You can create a file and put the following information into it filling in the servername,app name and db name
    ExecDB::"Planning/servername/appname/dbname"
    Save it as .xml file (don’t think it has to be an xml, could be .txt), so something like connect.xml
    Then when you run your command line do exactly like before Cmdlnlauncher -Sservername -Uusername -p:password.txt -rrule -fconnect.xml
    If you have variables in your rule you can
    In EAS right click over the rule and select "Automate Launch Variables", fill in the details and then save it is as an xml.
    You just need to reference the xml in the batch script as described above using the -f parameter, for sequences remove -rrule and use –sSequence
    update password.txt to the name of your password file.
    Cheers
    John
    http://john-goodwin.blogspot.com/
    Edited by: JohnGoodwin on Apr 30, 2010 8:17 AM

  • Runtime.exec() with envp[] array

    I ran into an unsual problem.
    If I set an env array variable to something (at least one pair), then certain applications fail to start through Runtime.exec(command[], env[]). For example, my own java classes that require various xml and ftp libraries. The particular exception has been mentioned on the forum ( ie. Unrecognized Windows Sockets error: 10106:).
    It has to do with environment variables not being set for new process. When I do NOT set env[] variable (or pass null) then current env is used in .exec() call and everything works fine.
    So my question is how do I set my environment variables and/or append them to existing set.Or said differently if I pass a non-null array, current env set is not copied over.
    thanks,
    eugene

    >
    It has to do with environment variables not being set for new process. When I do NOT set env[] variable (or pass null) then current env is used in .exec() call and everything works fine.
    So my question is how do I set my environment variables and/or append them to existing set.Or said differently if I pass a non-null array, current env set is not copied over.
    >
    If you're using 1.5, you can create a java.lang.ProcessBuilder object rather than calling Runtime.exec(). The ProcessBuilder inherits the environment of the calling process, but then allows you to update individual entries.
    In 1.4, I don't believe that you can get a complete copy of the invoker's environment.

  • Runtime.exec() with get command output

    hi,
    How can i get output of command which i run with runtime.exec().
    p.e.:
    Process p;
    Runtime r = Runtime.getRuntime();
    p = r.exec("net use \\pc\dir pswd /user:username");
    if command was done succesfully that in cmd is return this:
    "The command completed successfully." I can get this text, but i dont know how.
    Plese help
    thank you
    Palo

    Look at the API for Process

  • Runtime().exec( "ls output.file" ) does not work....

    I try the following program in RedHat linux 7.1. It return silently but no output.file is created? What can i do? Please help!
    //start of program
    public class s{
         public static void mainj( String args[] ){
              try{
                   Runtime.getRuntime().exec( "ls > output.file" );
              }catch( Exception e ){
                   e.printStactTrace();
    //end of program.
    The program return silently, but no output.file is created? what can i do? please help...

    I have tried to put the "ls > output.file" into a command.sh file, and change the line:
         Runtime.getRuntime().exec( "./command.sh" );
    But still, no output.file is created?
    What can i do....
    please help....

  • Runtime.exec with Unix script

    I want to execute unix script xxx.sh that I write it for running something and I will execute that script via java class I use
    Runtime runTime = Runtime.getRuntime();
    Process procRun = runTime.exec("/xxx/yyyy/testing.sh");
    xxx and yyyy is path in my unix server and testing.sh is unix script
    when I run this class it return true result but that unix script doesn't working or execute following my program in java class
    please help me to solve this problem
    Regards,
    sobig

    when I run this class it return true result but that unix script doesn't
    working or execute following my program in java classwhat do you mean it returns true....
    and how do you know that it does not execute your script.... its probably going to be started as a bg process.... try doing something like creating a directory or something in the script .sh to be sure that it ran.... (just for testing).... im quite sure that it will execute a .sh file like that....

  • Problems with .bat files [urgent]

    I have succed to do so that my java program can run a .dat file, but now I wonder what I should write in it.
    I want to run a file called Geo.class in a sub folder called \Subclasses, so what should I do?
    Here is the folder system:
    C:\java\runClasses.bat <--- It's here the .bat file should be
    C:\java\Subclasses\Geo.class <----- and here is the .class file that the bat file should execute
    So could anyone say what I should write in the .bat file for this to work?? It's very urgent!!

    It depends upon whether your Geo class is in a package or not. If you have a line that says "package Subclasses" (for instance) then you need to say "java Subclasses.Geo" in your bat file.

  • Runtime.exec with a unix shell script

    I've done a lot of google'ing and haven't found a definitive answer to my question, including the JavaWorld article that is pointed to quite often. Scenario1 - The program calling Runtime.exec is running in /dir1 and I have a script called test.sh in /dir2 (neither directory are in the path). If I call Runtime.exec("test.sh", null, "/dir2"), I get java.io.IOException: test.sh: not found. However, if I do "touch test.sh" AND "chmod +x test.sh" in /dir1 and call the same exec, it works AND runs the script in /dir2 not /dir1?!?! Also, if I copy /dir2/test.sh /dir1/test.sh and I call exec("test.sh"), it works fine. Scenario2 - If I get rid of /dir1/test.sh and call exec("/dir2/test.sh", null, "/dir2") OR exec("/bin/sh test.sh", null, "/dir2") - both of those work. I just don't get Scenario1. Why does having the dummy executable test.sh in /dir1 allow it to run in /dir2 OR if the script is in the local directory of the process calling exec, why does it work without adding the path? It doesn't seem consistent. Seems like the working directory I specify isn't set before trying to run it or something. On the flip side, if I have a java class in /dir2 called test.class, I can call exec("java test", null, "/dir2") and it just runs without jumping through any hoops - although I think the explanation for that is that "java" is in the path. Let me know what you think.
    Gary

    I think the problem is that the three argument version of exec specifies the command to run (should be full path to it if it is not in the current dir), the environment, then the working directory. The working directory will not help java to find the command to run in the first place. The following does work as you say:
    Runtime.exec("/bin/sh test.sh",null,"/dir2");This is because the full path to the command (/bin/sh) is specified, that runs in directory /dir2 then tries to find test.sh which it finds there.
    Basically to run anything, you should specify the full path in the command, the working directory will not help java find it.
    Dave

  • Runtime.exec with wget

    Hi,
    well i want to execute wget command in a java class and print sdout in the shell
    this is my code:
              try {
                   Process ls_proc = Runtime.getRuntime().exec("wget http://antimilkado.free.fr/ted/screenshot.png");
                   BufferedReader ls_in = new BufferedReader(new InputStreamReader(ls_proc.getInputStream()));
                   try {
                        while ((ls_str = ls_in.readLine()) != null) {
                             System.out.println(ls_str);
                   catch (IOException e) {
                        System.err.println(e);
                        System.exit(0);
              }I've tested with other basic command like ls and co., it works but not with a wget, nothing is printed...
    I guess my code is good and there is maybe a problem with wget command i don't know
    If someone gets it :)
    thx
    ++
    SHiSo

    1) Get the InputStream from the connection.
    2) Open a FileOutpupStream to the file you wish to write.
    3) Loop reading bytes from the InputStream and write them to the FileOutputStream until you get EOF.
    e.g.
    InputStream is = ...
    FileOutputStream os = ...
    byte[] buffer = new byte[4096];// or any size you want
    for (int count = 0; (count = is.read(buffer)) >= 0;)
    os.write(buffer, 0, count);
    4) flush() then close() the FileOuputStream.

Maybe you are looking for

  • QM interface with WM

    Hi Gurus, I Have a situation where transfer orders are generating based on the storage bin capacity. For example: when i used GR quantity 3000 LBs, TO is not generated and when i changed the quantity to 1000Lbs TO is generated. I believe, it has some

  • RETAIL vs. BULK

    im planning to buy a radeon 9500 pro and check the retail stores around for prices. for a retail version the price is around $200 or so but if its a bulk version it prices around $165-170 which is aroun 30-40 cheaper than retail. but wuts the differe

  • PATH_NOT_FOUND Root Cause while creating a declerative component - resolved

    While adding a new File System Connection , I have added the directory path where my declerative component jar is created it is in the path D:\workspace\mywork\TaskFlow\ViewController\deploy\myDeclerativeCompLib.jar I have cross verified the path the

  • Help! Pictures lost on my site

    I hope you are able to help me out. Yesterday I was looking back to postings that I made in my blog during February. I was looking into my site from the internet. I discovered, that some blogs were showing a big cross, instead of the picture that I p

  • Can I update the operating system on my Mac OSX 10.5.8

    How can I update my Mac OSX 10.5.8 to a newer operating system?