Running commands from the Command Prompt -  Runtime.getRuntime().exec()

Hi there,
I'm already able to run several commands in the command prompt.
But my problem is that I need all the commands that I run share the same context.
If, for example, I run "cmd /c set HOME=C:" (1st command), I want to be able to access that variable the next time, so that later when I run "dir %home%" it shows the directories in c: (This is just a example this is not what I really want to do...)
I used code posted in a newsgroup (don't remember which)
This is the code I use to execute commands:
     private int execute(String command)
     int exitVal = 0;
try
String nomeOS = System.getProperty("os.name" );
String[] cmd = new String[3];
if( nomeOS.equals( "Windows NT" ) || nomeOS.equals("Windows 2000") )
cmd[0]="cmd.exe";
cmd[1]="/c";
cmd[2]=command;
else if( nomeOS.equals( "Windows 95" ) )
cmd[0]="command.com";
cmd[1]="/c";
cmd[2]=command;
if (rt==null)
     rt = Runtime.getRuntime();
          Process proc = rt.exec(cmd);
          CommandStream erro = null;
          // erros?
          if (proc.getErrorStream()!=null)
               erro = new CommandStream(proc.getErrorStream());
               erro.start();
// output?
CommandStream output = new
CommandStream(proc.getInputStream());
// arranque
output.start();
// erros???
exitVal = proc.waitFor();
     } catch (IOException e)
               System.out.println("Exce !!!" );
               e.printStackTrace();
     catch (InterruptedException ie)
               System.out.println("Ocorreu uma excep��o !!!" );
               ie.printStackTrace();
return exitVal;      

My problem is bigger than setting a few parameters,
I'm doing a GUI to a CVS client and the problem is that some commands of CVS only work if you're in the right directory, or if you're authenticated, and all of this is easily done doing a series of execution:
In a command prompt opened I would:
set cvsroot=:pserver:lpinho@w2palf38:/project
cvs -d :pserver:lpinho:xxxxx@w2palf38:/project login
mkdir temp_my_proj
cd temp_my_proj
cvs checkout my_projectAll this would make what I wanted...
And there's another thing, when I set the envp, I get some errors like "cvs.exe is not recognized as an internal or external command" (the path went bye bye) and if I set the path (envp[0]="path=c:\cvsnt"), I'm able to run cvs but I get a crazy error "No such host is known" (I run exactly the same command in the command prompt and it works...)
Do you know any way of getting the current environment, and pass it as the envp parameter?
Thank You
Luis Pinho

Similar Messages

  • Is it possible to run Acrobat3D from the command line?

    I'd like to know if it is possible to run Arobat3D from the command line in batch mode. I'm interested in knowing if this is possible in either a windows or unix environment.
    My objective is to convert CAD data e.g. CATIA V5 or DXF etc to PDF, in batch mode without using the Acrobat3D interface itself.
    I know that it's possible to run a batch process from within Acrobat3D itself, therefore one solution may be to invoke those batch processes from the command line.
    I've looked through the other listings on this forum and seen this question asked previously, but I've not seen any responses that suggest this is even a feasible concept.

    As of now, it's not possible in the cmd-mode to just remain connected and not stream.
    But the reason you want to do that is because of the long start-up time. That 20 sec time can be divided into:
    1. launch time
    2. time to start encoding (after pressing start button) -> cannot be reduced even if 'connected only' feature is available in cmd-line
    Below are tips you can use to reduce this 20 sec of time:
    1. Lesser the no. of devices connected to the system, shorter is the launch time. Disable the devices which are not to be used in the session.
    2. Try using device indexes (0, 1, 2, etc) instead of device names in the profile. Indexes might change after you disable some of the devices.
    3. Use the profile with correct settings, to avoid any validation errors.
    4. Higher the video size, higher is the overall time. Small sizes take lesser time to start.
    Let me know if you see any improvement in the startup time.

  • How would you capture the stdout of Runtime.getRuntime().exec())?

    How would you capture the stdout of Runtime.getRuntime().exec())?
    Say you wanted to execute PKZIP25.exe from java using Runtime.getRuntime().exec(). How would you capture the output of PKZIP25 (the console IO) in a file so you could check the results?
    Thanks
    Bill Blalock

    Thanks.
    Could you explain a little more?
    The program I am calling seems to be executing, as far as Java is concerned, but nothing happens. I imagine I have made mistakes in calling it but can't see the output to the console.
    Should I use Runtime.getRuntime().exec() or Runtime.exec() for something like this?
    I appreciate the help!
    Bill B.

  • Reading commands from the command line

    Ok I've read quite a bit about streams, and I get the gist that you are suppose to open up a "stream," whether it from a file or from something else, and then you have to do all sorts of stuff to it like activate it or something, or whatever. But all I want to do is take an input from the command line, for example my name, and have it output "Hi [name]." I could swear I've done this before with a simple command like
    System.in.read() or something like that, but I read up on it and read is not a method that does that? So how does one just do a simple command line input into a variable...for what I want to do is control movement on a maze. If somebody can direct me to some documentation I would be happy as well. Thank you

    btw - "deadseasquirrels" - like the name. Have another program;-
    import java.io.*;
    import java.util.Random;
    public class Do_Writing {
       public static void main( String args[] ) throws IOException {
       BufferedReader in = new BufferedReader
                           (new InputStreamReader(System.in));
       Random rand = new Random();
       int i = 1+ rand.nextInt(10);
       String s1;
       System.out.println("Guess a number between 1 and 10");
          try {
             while ((s1 = in.readLine() ) != null) {
                // if( ... I'll leave the rest to you to figure out
                // when they get it right don't forget to include;-
                System.exit(0);
                in.close();
       catch (IOException ignore) { }                     
    }

  • Jar file runs from the command line, but not when I double click it

    Hello, I'm running windows xp. I've created an executable jar file and it runs fine from the command line when I type;
    java -jar wizard.jar
    but, when I double click it . . . nothing.
    Any ideas?

    nothing ? that's weird, windows XP should prompt you to select the program you want to use in order to open Jar files (and give you this silly piece of advice to search the web for the appropriate program)
    you might want to check what program (if any) got associated with .jar extensions :
    in Windows Explorer : Tools => Folder Options => File Types
    hth

  • Problem with running a java program from the command line

    I have this code:
    package pkg;
    import jxl.*;
    import java.io.File;
    public class TestClass {
         public static void main(String[] args) {
              try{
                   Workbook book = Workbook.getWorkbook(new File("d:/testWorkspace/excFile.xls"));
                   Sheet sheet = book.getSheet(0);
                   String s=sheet.getCell(4, 2).getContents();
                   System.out.println(s);     
              }catch (Exception e){System.err.println(e);}
    }I've wrote it in Eclipse, added jxl.jar to the buildpath, and it works fine.
    Then I tried to run it from the command line and I did it like this:
    D:\testWorkspace\testProject\bin> java -cp \jxl.jar pkg.TestClassThe result was:
    Exception in thread "main" java.lang.NoClassDefFoundError: pkg/TestClass
    Caused by: java.lang.ClassNotFoundException: pkg.TestClass
    ...but the file TestClass.class DOES exist in the folder d:\testWorkspace\testProject\bin\pkg\ and the file jxl.jar IS on the root of drive D (like I already wrote, it worked fine inside the Eclipse).
    So, my question is: How to run this code from the command line?
    I have no idea what went wrong.
    Can someone help me, please?

    The current directory is not implied in the classpath.
    D:\testWorkspace\testProject\bin> java -cp .;d:\ pkg.TestClassor
    D:\testWorkspace\testProject\bin> java -cp .;d:\jxl.jar pkg.TestClassI always forget which is right since I never work with jars...

  • Run javascript (not in a jsx file) from the command line extendscript

    Hi all,
    I was wondering if anyone knew how to run javascript from the command line in Extendscript (meaning Extendscript would be the target application). I know about the -run command line flag in which allows you to run a .jsx script from the command line but what I'm looking for similar syntax to run a script directly without needing to put it in a file. For example I have tried (obviously unsuccessfully):
    C:\Program Files (x86)\Adobe\Adobe ExtendScript Toolkit CC\ExtendScript Toolkit.exe -run "alert('Hello World');"
    Thanks!

    You might be looking for something like this: javascript - Is it possible to execute JSX scripts from outside ExtendScript? - Stack Overflow
    Although that one is about executing JSX files, the solutions given (Applescript as well as COM/VBScript) can be adapted to simply run a javascript code snippet rather than JSX file because the solutions simply call the Adobe app's Applescript/COM API to "execute javascript" (actually execute ExtendScript technically), and in the solution, they using includes to pull in the JSX file. You'd simply replace the include with actual javascript code snippet inserted in.
    Though this would then require you to run a VBScript, Applescript, or other script (that calls the COM/Applescript API) rather than the ESTK command line option.

  • Runtime.getRuntime().exec(Command) problems...

    hi, i am trying to run a NET USE command through using:
    Runtime.getRuntime().exec(Command);
    where Command is a valid NET USE command. I know it is valid because i executed this exact command
    from the command line and it worked fine. This class works perfectly under Windows, but then i took it to an
    OS/2 environment and i am getting this error. Does anybody know what i need to do to modify so it will work
    under OS/2? any gotchas? thanks

    i read that article, and there is a lot to go over. I will start that right now. Anyways, i got the actual stack trace
    from this error:
    at java.lang.Win32Process.create(Native Method)
    at java.lang.Win32Process.<init>(Win32Process.java:67)
    at java.lang.Runtime.execInternal(Native Method)
    at java.lang.Runtime.exec(Runtime.java:566)
    at java.lang.Runtime.exec(Runtime.java:428)
    at java.lang.Runtime.exec(Runtime.java:364)
    at java.lang.Runtime.exec(Runtime.java:326)
    at ReconnectReportServer.run(ReportServer.java:499)
    at java.lang.Thread.run(Thread.java:536)
    and, once again, i am running this on OS/2. I compiled it on OS/2 as well. Any ideas? thanks!

  • Executing a command by Runtime.getRuntime.exec().

    Hi,
    I am try to run a java command from one java program. Is it possible
    eg :
    public class A {
    public static void main(String[] args) {
    String startjvm ="java -classpath E:\classes B";
    Runtime.getRuntime.exec(startjvm);
    public class B {
    public static void main(String[] args) {
    System.out.println("Inside the main for class B");
    when i execute the above command from the command line it executes,but when are run the main method for class A nothing happens meaning the message : "Inside the main for class B" is not displayed.
    I also tried displaying the int returned by process.waitfor() method. process is the object returned by the Runtime.getRuntime.exec() method. The int returned is 0 which means the process terminated previously.
    Thanks in advance

    You could get InputStream from created Process and read
    information from it.
    For example
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    public class A {
        public static void main(String[] args) {
            try{
                String startjvm ="java -classpath E:\\classes B";
                Process s = Runtime.getRuntime().exec(startjvm);
                BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
                String line = "";
                while ((line = in.readLine()) != null) {
                    System.out.println(line);
                in.close();
            }catch(Exception e){
                e.printStackTrace();
        }

  • How to create an alias from the command line

    Hi
    I would like to know how to create an alias (for a file, not a command) from the command line. I don't want to use the ln command, as an alias has more interesting features than soft/hard links... Is there an Apple specific tool to do this?
    Thanks
    -Jerome
      Mac OS X (10.4.10)  

    The only straightforward way that I am aware of for creating a "Finder" alias from the command line is using AppleScript via 'osascript'. Of course, it's not really a command line solution since the "Finder" has to be running. Anyway, something along the lines of:
    <pre style="overflow:auto; padding: 5px; width: 500px ; font-size: 10px; border:1">osascript -e 'tell application "Finder" to make alias file to POSIX file "/full/path/to/file" at POSIX file "/full/path/to/folder"'</pre>

  • Runtime.getRuntime().exec hangs and doesn't print the output

    Hi,
    I have written the following code to execute the command "psexec ipaddress -u userid -p password -l -c execute.exe >> c:/25_showoutpout.txt" and print the output in 25_showoutpout.txt file.
    import java.io.*;
    public class ExecTest{
         public static void main(String args[]) throws IOException{
         String args1 = "psexec ipaddress -u userid -p password -l -c execute.exe >> c:/25_showoutpout.txt";
         try{
         Process p=Runtime.getRuntime().exec(args1);
    int i = p.waitFor();
         System.out.println("Done.with time "+i);
         }catch(Exception e){
              System.out.println("The error is "+e);
    But this program hangs and creates a blank 25_showoutpout.txt file.In the process list I can see the process running, but it doesn't redirect the output in the txt file.When i run the command from the command line it runs fine.Please help me.
    Thanks in advance

    Hi,
    I have written the following program to get the output.But still the required output is not coming in the console file.Only the messages that gets printed in the parent console that is coming in the file.But the expected output is to get the messages from the child window which gets executed while the .exe runs.
    import java.io.*;
    public class RuntimeExecTest{
    public static void main(String args[]){
    String s = null;
    String result= null;
    int count =0;
    try{
              // read the output from the command
    String cmd = "cmd.exe /c D:/installer/PsTools.zip/PsTools/psexec.exe ipaddress -u userid -p password -l -c excute.exe >> C:/RuntimeExec_25.txt";
         Process p = Runtime.getRuntime().exec(cmd);
         InputStream is = p.getInputStream();
         // Get the std in to the process.
         OutputStream os = p.getOutputStream();
         // Get the std err from the process.
         InputStream es = p.getErrorStream();
         // Create readers for those streams.
         BufferedReader reader = new BufferedReader(new InputStreamReader(is));
         BufferedReader errReader = new BufferedReader(new InputStreamReader(es));
         String line;               
         // Read STDOUT into a buffer.
         // If no STDOUT check STDERR.
         while((line = errReader.readLine()) != null){
              // Do something with data here if you wish.
         System.out.println( line );
         while((line = reader.readLine()) != null){
              // Do something with data here if you wish.
         System.out.println( line );
         System.exit(0);
    catch( Exception ex )
    ex.printStackTrace();
    }

  • Runtime.getRuntime().exec - relies on the J2RE?

    Well here is a problem...
    My program works fine using the Runtime.getRuntime().exec command, and the program works as-intended on my computer. But that's because I have the latest and greatest Java apparel (especially the J2RE).
    Now, a friend of mine who does not program, took my program and tried it on his computer. It worked (the GUI loaded and buttons functioned) but it didn't actually do anything other than serve as a nice-looking GUI lol.
    The problem was, it was creating the file I had it create (using FileWriter) but it wasn't EXECUTING that file like I designed the program to.
    I used the Runtime.getRuntime().exec to execute the file - my question is, if the person doesn't have the Java Runtime Environment, will that command work? He clearly has Java on his computer (the GUI loaded) but he might not have the J2RE...
    Any thoughts? Any suggestions for an alternative way to execute a file?
    Thanks!
    -Josh

    I don't understand why this wont work on other
    people's computers...
    I create the file "commands.bat" in their C:\
    directory. I then have the following command to
    execute it:
    Runtime.getRuntime().exec("cmd.exe /c
    \"C:\\crasher.bat\"");It works perfect for me... But it doesn't work for
    other people. For other people, it creates the batch
    file in the right place, it just wont execute it and
    I am not sure why...
    -JoshYou said "commands.bat" but your code is executing "crasher.bat". I have the feeling you're trying to crash their computers or something?
    cmd.exe is an executable on certain flavors of Windows. Other flavors of Windows have command.exe, not cmd.exe. So you have to pick the same platform, or make the actual command that you execute be dynamic (read it from a property file to determine what to execute).
    Go to those other machines and see if you can execute that same command from the command line. Do some debugging for pete's sake.

  • Problems with Runtime.getRuntime().exec in Windows 2000

    Hello,
    I have a batch file that I want to run from my java application. My code is the following:
    try {
            Runtime.getRuntime().exec("cmd.exe /c C:\\temp\\shortcut.bat");
    } catch (Exception e) {
         System.out.println(e.getMessage());
    }I was developing on windows XP and it worked just fine. But then I tested it on windows 2000 and it didn't work. The batch file is okay, because if I run the batch file myself it works just fine, even from the command line. I get no errors what so ever, it just doesn't do anything...
    Can somebody help me with this?
    thx in advance

    thank you all so much
    I figured it out... It was a combination of two things that went wrong.
    First one: in my batch file I had:
    cd C:\tempwhich worsk fine in XP, but in it doesn't in 2000. In 2000 it has to be:
    C:
    cd \temp But just changing that wasn't enough, I also needed the "start"
    Now it works just fine on 2000, hopefully it'll still work on xp as well.
    THX!

  • Runtime.getRuntime().exec() does not return

    Hello,
    I am running into a case where the call to Runtime.getRuntime.exec(command) does not return. The scenario is that the main thread spawns another thread which calls the Runtime.exec(). Since the call does not return, both threads seems to be hung. The jstack output from the main thread shows
    ----------------- t@2 -----------------
    0xfeedab45 ___lwp_cond_wait + 0x15
    0xfeb4030d void os::PlatformEvent::park() + 0xa9
    0xfebadd48 void ObjectMonitor::wait(long long,bool,Thread*) + 0x26c
    0xfe770287 void ObjectSynchronizer::wait(Handle,long long,Thread*) + 0xef
    0xfe76ffbb JVM_MonitorWait + 0x20f
    0xfb20a032 * java.lang.Object.wait(long) bci:0 (Interpreted frame)
    0xfb20308d * java.lang.Thread.join(long) bci:38 line:1143 (Interpreted frame)
    0xfb20308d * java.lang.Thread.join() bci:2 line:1196 (Interpreted frame)
    0xfb20308d * DataLoader.checkThreadGroup() bci:92 line:316 (Interpreted frame)
    0xfb202f27 * DataLoader.checkTables(int) bci:1 line:336 (Interpreted frame)
    0xfb202f69 * DataLoader.runLoad(int, java.lang.String, java.lang.String, java.lang.String, com.sabre.fltsked.apm.util.FSIOHelper)
    ... more below ....
    So it is waiting for the spawned thread on a join()
    And the jstack dump for the thread that called exec() is
    ----------------- t@70 -----------------
    0xfeed7409 __lwp_park + 0x19
    0xfeed1be7 cond_wait_queue + 0x5e
    0xfeed1f64 cond_wait_common + 0x1db
    0xfeed20d2 condwait + 0x7b
    0xfeed20fd cond_wait + 0x21
    0xfeed2136 pthread_cond_wait + 0x1b
    0x9741082a soft_delete_object_cleanup + 0x57
    0x97410906 soft_delete_object + 0x5b
    0x97410953 soft_delete_all_objects_in_session + 0x2e
    0x97407b7a soft_delete_session + 0xec
    0x97407860 soft_delete_all_sessions + 0x3c
    0x97402525 finalize_common + 0x66
    0x974026ae softtoken_fini + 0x34
    0x974355f9 _fini + 0x21
    0xfefdd49a remove_hdl + 0x766
    0xfefd8be9 dlclose_core + 0xb1
    0xfefd8c1d dlclose_intn + 0x21
    0xfefd8c96 dlclose_check + 0x2a
    0xfefd8d00 dlclose + 0x38
    0x97480aeb pkcs11_slottable_delete + 0xb1
    0x9747c691 finalize_common + 0xe2
    0x9747c6e0 pkcs11_fini + 0x3e
    0x9747c3bf pkcs11_fork_child + 0x73
    0xfee628b8 postforkchild_handler + 0x2f
    0xfeeca9ec fork + 0x12e
    0xfe338029 Java_java_lang_UNIXProcess_forkAndExec + 0x395
    0xfb20a032 * java.lang.UNIXProcess.forkAndExec(byte[], byte[], int, byte[], int, byte[], boolean, java.io.FileDescriptor, java.io.FileDescriptor, java.io.FileDescriptor) bci
    :0 (Interpreted frame)
    0xfb202f69 * java.lang.UNIXProcess.<init>(byte[], byte[], int, byte[], int, byte[], boolean) bci:62 line:53 (Interpreted frame)
    0xfb20308d * java.lang.ProcessImpl.start(java.lang.String[], java.util.Map, java.lang.String, boolean) bci:182 line:65 (Interpreted frame)
    0xfb202f27 * java.lang.ProcessBuilder.start() bci:112 line:452 (Interpreted frame)
    0xfb202f27 * java.lang.Runtime.exec(java.lang.String[], java.lang.String[], java.io.File) bci:16 line:593 (Interpreted frame)
    0xfb202f27 * java.lang.Runtime.exec(java.lang.String, java.lang.String[], java.io.File) bci:69 line:431 (Interpreted frame)
    0xfb202f27 * java.lang.Runtime.exec(java.lang.String) bci:4 line:328 (Interpreted frame)
    0xfb202f27 *SQLLoad(java.lang.StringBuffer) bci:181 line:51 (Interpreted frame)
    0xfb202e61 *FSLoadThread.run() bci:84 line:54 (Interpreted frame)
    The command I am trying to exec is "sqlldr" and I do have it in my PATH variable. Why is that the call to exec does not return? Any ideas?
    This is on jdk1.6.0_17
    Thanks,
    Bijoy.

    It has definitely forked, and this is the child process. It says so. If it was the parent process it would just show Java code related to launching processes. That does not involve PKCS11. After the fork there are two identical processes with the same stack: the child process of the fork goes on to replace itself with the target command via Unix exec(), which it doesn't look like it is succeeding at. The parent process doesn't do much at all, probably just housekeeping and then a Unix wait() for Process.waitFor() to hook into.

  • Runtime.getRuntime().exec portability problem

    Hello everyone!
    I've got a problem with running external application (in my case it's pdfLaTeX). The code looks as follows:
    System.out.println(AppConfig.getExeFile() + " " + params); // AppConfig.getExeFile() is a static function that outputs a String object.
    Process p = Runtime.getRuntime().exec(AppConfig.getExeFile() + " " + params); // params is a String object as well.
    p.waitFor();
    // ...On Linux everything works great. System.out.println() outputs the following line:
    /opt/texlive/bin/pdflatex -halt-on-error   -output-directory /tmp   /tmp/tabular.texThe application executes successfully.
    However, I can't get my program to run on Windows. In this case, the generated command looks as follows:
    "C:\Program Files\LaTeX\MiKTeX 2.7\miktex\bin\pdflatex.exe" -halt-on-error   -output-directory C:\DOCUME~1\Roman\USTAWI~1\Temp   C:\DOCUME~1\Roman\USTAWI~1\Temp\tabular.texAfter displaying this line, my application freezes. The child process (pdflatex.exe) is frozen as well. Then I kill both processes.
    Here's the PdfLaTeX's log file after failure:
    {C:/Documents and Settings/All Users/Dane aplikacji/MiKTeX/2.7/pdftex/config/pd
    ftex.map}
    !pdfTeX error:  (file C:/Documents and Settings/All Users/Dane aplikacji/MiKTeX
    /2.7/pdftex/config/pdftex.map): fflush() failed
    ==> Fatal error occurred, no output PDF file produced!and here's how it should look like:
    {C:/Documents and Settings/All Users/Dane aplikacji/MiKTeX/2.7/pdftex/config/pd
    ftex.map}] (tabular.aux) )
    Here is how much of TeX's memory you used:
    202 strings out of 95340
    2116 string characters out of 1183965
    46926 words of memory out of 1500000
    3474 multiletter control sequences out of 110000
    3640 words of font info for 14 fonts, out of 1200000 for 2000
    14 hyphenation exceptions out of 8191
    23i,6n,17p,173b,100s stack positions out of 5000i,500n,10000p,200000b,5000s
    <C:/Program Files/LaTeX/MiKTeX 2.7/fonts/type1/bluesk
    y/cm/cmr10.pfb>
    Output written on tabular.pdf (1 page, 10003 bytes).
    PDF statistics:
    10 PDF objects out of 1000 (max. 8388607)
    0 named destinations out of 1000 (max. 131072)
    1 words of extra memory for PDF output out of 10000 (max. 10000000)I suspected that the problem was caused by presence of spaces in command (I've tried several other solutions such as putting parameters into String[] array, escaping, adding double-quotes, putting the command to the batch file), but when I run my the same command from the command line, everything works fine.
    I believe that I'm making some kind of a stupid mistake because it doesn't look like it's pdfLaTeX's fault.
    Thanks in advance for your hints. Solutions are welcome as well ;-)

    Hi,
    What is probably happening is that the process is being blocked because you are not reading the output.
    This is a common problem with exec.
    Read this article:
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
    HTH,
    Eugenio Alvarez

Maybe you are looking for