Using Runtime to call a number of commands in one session

Hi,
I've got a windows BAT file which sets up the Windows environment variables needed to run a command line program. When using this manually I just have a shortcut which calls "cmd /k c:\blah\mybat.bat" and opens a command line windows I can use to work in. How can I do the equivalent from within my Java code?
I understand that I can use Runtime as follows:
Process pr = rt.exec("cmd \"C:\\Program Files\\FWTools2.4.4\\setfw.bat\"");
BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line=null;
while((line=input.readLine()) != null) {
     System.out.println(line);
}But I also need to run a command line program from within the same session (otherwise it won't work, as the environment variables are not set). The other command I need to call is:
Process  pr = rt.exec("gdal_merge -o " + outTif + " -separate " + inTif);How can I call both of these in one command line session?
I hope that makes sense :S
Thanks,
Jon
Edited by: DeadPassive on Oct 7, 2009 7:11 AM

Use Runtime.exec() to invoke cmd.exe and then write the sequence of commands to the process stdin. You should handle both stdout and stderr in separate threads. If you have not done so already, you should read the 4 sections of [http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html|http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html] and you should implement the recommendations.

Similar Messages

  • NoClassDefFoundError when using Runtime to call a shell script

    I have a java program that uses the Runtime.exec method to call a shell script that then calls another java program (the shell script and 2nd java program are a 3rd party product I have to call).
    When I run my program as root, it works fine. When I run it as a regular user, I get the following error message:
    Exception in thread "main" java.lang.NoClassDefFoundError: 'argument'
    In the error message above, "argument" is just an argument I had to pass to the shell script, which then calls the 2nd java program. It is this second java program that is throwing this exception it seems. This is all in Linux (RH AdvSrvr 2.5). If I call the shell script on the command line as the regular user, not from the java program, it works fine; but I NEED to call it from the java program... it's a long story.
    I have check Environment variables, system properties under both users during the processes and I cannot find any major difference. I have checked file permissions and everything.
    Does anybody have a clue what is going on here? Please help me, thank you!

    Okay, we found the problem. Our in-house MASTER OF ALL found it. The argument that the jvm was trying to load as a class needed to be in quotes according to documentation, but the shell escapes out the quotes when run on the command line, whereas in my java process it was not, therefore the jvm thought it needed to load it as a class.
    Clear as mud?

  • How to use AT LINE-SELECTION and AT USER-COMMAND in one report????

    Dear all,
    I have a problem in reports I want to use AT USER-COMMAND.and AT LINE-SELECTION.both in the one report.
    But as soon as I use SET PF-STATUS my AT LINE-SELECTION event stop workingand only AT USER-COMMAND is working.
    How can I use both of them in one report for your reference I am giving my test program below.
    REPORT ZTEST111 .
    SET PF-STATUS '100'.
    DO 10 TIMES.
    WRITE:/ SY-INDEX.
    HIDE SY-INDEX.
    ENDDO.
    START-OF-SELECTION.
    AT LINE-SELECTION.
    MESSAGE I002(SY) WITH SY-INDEX.
    AT USER-COMMAND.
    MESSAGE I002(SY) WITH 'USER COMMAND'.
    END-OF-SELECTION.
    Thanks in advance
    Sachin Gautam

    hi
    Syntax
    AT USER-COMMAND.
    Effect
    This statement defines an event block whose event is triggered by the ABAP runtime environment if, during the display of a screen list, a function with a self-defined function code was chosen.
    Note
    Self-defined function codes are all those that include character combinations, except for the following:
    The function codes PICK and PF## ("##" stands for 01 to 24) do not cause the event AT USER-COMMAND, but the events AT LINE-SELECTION and AT PF##.
    All function codes that start with the character "%" are interpreted as system functions and do not cause the event AT USER-COMMAND. The system functions for lists are listed in the following table 1.
    The function codes in the following table 2, likewise, do not cause the event AT USER-COMMAND, but are handled by the list processor.
    Table 1
    Function code Function
    %CTX Call a context menu
    %EX Exit
    %PC Save to file
    %PRI Print
    %SC Search for ...
    %SC+ Find next
    %SL Search in office
    %ST Save to report tree
    Table 2
    Function code Function
    BACK Back
    P- Scroll to previous page
    P-- Scroll to first page
    P+ Scroll to next page
    P++ Scroll to last page
    PFILE name Store list lines in a text file named abap.lst in standard character representation in the standard directory of the application server. If a name is entered using name, this is converted to lowercase letters and used as the file name.
    PL- Scroll to first line of the page
    PL-n Scroll n lines back
    PL+ Scroll to last line of the page
    PL+n Scroll n lines up
    PNOP No effect
    PP- Scroll back one page
    PP-n Scroll n pages back
    PP+ Scroll one page forward
    PP+n Scroll n pages forwad
    PPn Scroll to beginning of page n
    PRI, PRINT Print
    PS-- Scroll to first column
    PS++ Scroll to last column
    PS- Scroll one column to the left
    PS-n Scroll n columns to the left
    PS+ Scroll one column to the right
    PS+n Scroll n columns to the right
    PSn Scroll to column n
    PZn Scroll to line n
    RW Cancel

  • 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.

  • Running ssh in xterm using Runtime.exec !! URGENT

    I am not able to run the following command using Runtime.exec() but if the same command is executed in shell it gets executed.
    I am working on solais 8
    String toExecStr =
    "xterm -e /bin/sh -c \"ssh [email protected] || echo SSH failed. Press any key to quit.; read a \"";
    System.out.println("Running command :" + toExecStr);
    try {
    Process p = Runtime.getRuntime().exec(toExecStr);
    catch(Exception e){
    e.printStackTrace();
    Any clues .. am i missing something Is there some problem with solaris command ..

    Can some body help me solve this ???

  • My phone gets heat like ****, while charging, while using attending a call and playing games

    my phone gets heat like ****, while charging, while using attending a call and playing games, can some one help me out of this?

    Basics from the User Guide are restart, reset, restore.  Try each of these.  If they don't work, bring your phone into Apple for evaluation.

  • Help please! [using Runtime.exec() to run find command in UNIX]

    Hi guys! im trying to use exec() to run the UNIX find command
    that my application uses. As you can see from my sample code, the find command finds all files ending with html in my home directory. Unfortunately when I run the program it doesn't give me an output, but when I run it on the shell in the same directory as this code is saved, it works perfectly fine.
    Could someone please help me on this one. Many thanks! =)
    import java.io.*;
    import java.lang.String;
    public class RunCommand {
            public static void main(String[] args) {
                    try {
                            String[] command = {"find", "~/", "-name",
                                            "*.html", "-print"};
                            String find_str;
                            Process find_proc = Runtime.getRuntime().exec(
                                            command);
                            DataInputStream find_in = new DataInputStream(
                                            find_proc.getInputStream());
                            try {
                                    while ((find_str = find_in.readLine())
                                                                    != null) {
                                            System.out.println(find_str);
                            } catch (IOException e) {
                                    System.exit(0);
                    } catch (IOException e1) {
                            System.err.println(e1);
                            System.exit(1);
                    System.exit(0);
    }

    I don't see anythi obvious. In both catch blocks, call printSckTrace on the exception yhou caught.
    I think the real culprit is the ~ though.
    ~ is interpreted by some (most?) shells to men home dir. However, when you just exec a command, you don't have a shell to do that interpretation for you, so it's looking for a directory that's literally named ~.
    Either exec a shell (read the man pages for the shell of your choice, but for zsh I think it's "/bin/zsh -c find ~ blah blah blah) or else just put the actual path to your home directory into the string you pass to exec. You can get that from System.getProperty("user.home").

  • How can I activate an old version of Photoshop that I've loaded on my new tablet? The web activation doesn't work, and when I call the number, it says it's not being used anymore. Meanwhile, I'm down to 13 days till it stops working due to not being activ

    How can I activate an old version of Photoshop that I've loaded on my new tablet? The web activation doesn't work, and when I call the number, it says it's not being used anymore. Meanwhile, I'm down to 13 days till it stops working due to not being activated. HELP?  I really need to continue using this product for my home business.It works fine not activated but the threat is that it will stop working in 13 more days if I don't get it activated, and none of the activation methods they list seem to work.

    The new serial number is to the right of your chosen download.

  • Executing a command using Runtime Class

    How to execute a command on a differnet machine with different ipaddress using Runtime Class
    My code is
    String[] cmd = new String[3];
    cmd[0] = "192.1...../c:/WINNT/system32/cmd.exe" ;
    cmd[1] = "/C" ;
    cmd[2] = args[0];
    Runtime rt = Runtime.getRuntime();
    System.out.println("Execing " + cmd[0] + " " + cmd[1]
    + " " + cmd[2]);
    Process proc = rt.exec(cmd);
    // any error???
    int exitVal = proc.waitFor();
    System.out.println("ExitValue: " + exitVal);
    This is not Working

    I have same issue. Actually when I use cmd.exe /c set in java code and if I run the java code in DOS propmt, it retrieves all latest user Environment variable values. But if I run the code in windows batch file, it is not retrieveing the latest user environment values until I reboot my computer, Do you know how to get user environment value with out rebooting machine??????

  • I bought my iPhone 4s in the Uk and then brought to Cyprus where I live. I used Siri to call my husband 2 days ago without problem but now when I try to use Siri it won't call any local Cypriot number but will call my Uk contacts. Help please

    I bought my iPhone 4s in the Uk and then brought to Cyprus where I live. I used Siri to call my husband 2 days ago without problem but now when I try to use Siri it won't call any local Cypriot number but will call my Uk contacts. I can call the same numbers manually so it's not my network. Any help would be appreciated.

    This sounds like an international issue? Although I can not see why? I brought my phone in Australia and operating it in Indonesia, I have the same issues.... Otherwise Siri works fine, even texting (SMS) to local numbers siri works well, but dialing local number it just wont work...! I will try using my Australian SIM card and see if that is the reason.. I tried changing the number in the contacts and took out the international prefix, I turned the international assist on and off still nothing.. How frustrating. I called apple, the technican had know idea and we to his supervisor, had to wait fro 40 miuntes and then I hung up..
    PLEASE HELP..!

  • WHAT ABOUT FACE TIME?  I'D LIKE TO KNOW IF YOU NEED A PHONE NUMBER FOR YOURSELF TO USE IT TO CALL FROM YOUR COMPUTER

    WHAT ABOUT FACE TIME?  I'D LIKE TO KNOW IF YOU NEED A PHONE NUMBER FOR YOURSELF TO USE IT TO CALL FROM YOUR COMPUTER

    Do you have iMessage? I think as long as that person has iMessage you can use Face Time to call each other.

  • How to run db2 command by using Runtime exec

    Hello
    I am using java. When i am runing db2 command by using Runtime.exec( String cmd, String[] env ). I gave the environment path
    DB2CLP=6259901
    DB2DRIVER=D:\ibm\db2\java\db2java.zip
    DB2HOME=D:\ibm\db2
    DB2INSTANCE=DB2
    DB2MMTOP=D:\CMBISS
    but still I am getting error message
    "DB21061E Command line environment not initialized"
    after setting the above path in the cmd It is working fine. When i am trying thro java programm i am getting the above error. Can I get answer for this.
    bhaski.

    Before you can execute DB2 commands you have to open a DB2 CLP. The following code will do so:
    import java.io.IOException;
    public class Db2 {
         public static void main(String args[]) {
              try {
                   Runtime rt = Runtime.getRuntime();
                   Process child = rt.exec("db2cmd");
                   child.waitFor();
              catch (IOException io) {
                   io.printStackTrace();
              catch (InterruptedException e) {
                   e.printStackTrace();

  • In Siri, I can call by my voice, but why I can not use Siri voice call in my country (Laos), just can call only us phone number; my country we use like 3 number for option call, 8 numbers for call friend but Siri cannot use this please help us, thanks

    In Siri, I can call by my voice, but why I can not use Siri voice call in my country (Laos), just can call only us phone number; my country we use like 3 number for option call, 8 numbers for call friend but Siri cannot use this please help us, thanks
    And please help me can type Laos font in it like andrio phone.

    Hi Cozumel,
    Thanks for posting. I'm sorry you're having problems with your bills. I can take a look at this for you. Drop me an email with your account details and a link to this thread for reference. You'll find the address in my profile.
    Cheers
    David
    BTCare Community Mod
    If we have asked you to email us with your details, please make sure you are logged in to the forum, otherwise you will not be able to see our ‘Contact Us’ link within our profiles.
    We are sorry but we are unable to deal with service/account queries via the private message(PM) function so please don't PM your account info, we need to deal with this via our email account :-)

  • How to use runtime.exe to activate the native file coping commands

    How to use runtime.exe to activate the native file coping commands.(It might include using process(), and such.. but how?

    Why would you want to do this? It's harder than copying the file in Java (by reading the file and writing it to a new file) and you'll need to write new code each time you want to port your code to a new OS.

  • How to invoke the command interpreter to run the "NS.exe" using Runtime?

    hi,everyone
    I need to invoke the command interpreter,and enter the disk directory "c:/ns2/bin/",then run the "ns myfilename" command.My program is followed:
    try{
    String s[]=new String[4];
    s[0]="cmd.exe";
    s[1]="/c";
    s[2]="cd c:/ns2/bin";
    s[3]="ns.exe c:/ns2/bin/100n-500k-5.tcl";
    Runtime R=Runtime.getRuntime();
    Process p=R.exec(s);
    int exitVal = p.waitFor();
    System.out.println("Process exitValue: " + exitVal);
    But this doesn't work!
    please help me! thanks!

    hi,everyone
    I need to invoke the command interpreter,and
    and enter the disk directory "c:/ns2/bin/",then run
    the "ns myfilename" command.My program is followed:
    try{
    String s[]=new String[4];
    s[0]="cmd.exe";
    s[1]="/c";
    s[2]="cd c:/ns2/bin";
    s[3]="ns.exe c:/ns2/bin/100n-500k-5.tcl";
    Runtime R=Runtime.getRuntime();
    Process p=R.exec(s);
    int exitVal = p.waitFor();
    System.out.println("Process exitValue: " +
    alue: " + exitVal);
    But this doesn't work!
    please help me! thanks!CDing will not change the directory.
    should write:
    String cmd= "cmd /c c:\\ns2\\bin\\ns.exe c\\ns2\\bin\\100n-500k-5.tcl"
    for further details on how to use Runtime.exec(), see http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html

Maybe you are looking for

  • Posting to G/L account in Next period & Opening balances

    We need to post to G/L accounts for new Company code 1) During month of February , Can we post to GL accounts(FB50)  with Posting date in January? -->  if we have Period 1,2008 open in OB52 ( FROM Period 1,2008 TO Period 2,2008) 2) Is there a way tha

  • What exactly is the difference between enqueue,latch & lock

    Can someone explain in simple words (with example if possible) what exactly is the difference between enqueue,latch & lock? I have gone through documentation & other links,but just not able to figure out the exact & clear difference between these thr

  • Problems mounting usb Maxtor disk Help PLZ

    Usb maxtor disk that already has 2 OSX partitions does not want to mount in 10.4.9 updated mac mini. Disk utils in 10.4.9 is smoking some weed and does not / or want to do anything with the usb Maxtor. Tried on windows with Macdrive 7.0.4 trail and n

  • New Release - WD My Cloud EX4100 Firmware Release 1.06.133 (7/8/15)

    WD is happy to announce the release of its latest WD My Cloud EX4100 Firmware Update. You can post your experiences here in the My Cloud Expert Series forum. Please create individual topics for any questions that arise. Also please note the firmware

  • Firefox disappered from my desk top -it will not come back after new download, help

    I got reminders of new updates. I tried several times but it never completed the process after a huge time lapse. Now it disappeared from my icons and could not be retrieved so I tried to download Firefox again. It appears to download ..then nothing.