Running a command by Runtime class on Unix system

Hi,
To run a command in Windows I wrote the following code:
String s = "cmd.exe /C " + AnyCommand;
Process p = Runtime.getRuntime( ).exec( s );
For Unix system, what do I need to replace the "cmd.exe /C"?
Thank you

I am not familiar with Unix.
I've tried "bash", but that diesn't work
The AnyCommand is a compiling command "javac
className.java"Well, javac is an executable. So you don't need a command shell around it to run it, unless you want certain things like redirecting standard output to a file, such that the command shell provides. Just pass "javac className.java". (Now next question will be why doesn't it work, because you also have to take into account the current directory from which you launched javac, and so forth)

Similar Messages

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

  • Running interactive command with Runtime.exec

    I'm trying to run a command via the Runtime.exec interface.
    Occasionally, the command needs to prompt for additional information. The response depends on the specific configuration, however, the command returns a list of options and then waits for a response.
    However, when the command waits for the response, my Java app hangs.
    After I call Runtime.exec, I create 2 threads to consume the contents of stderr and stdout. I then start them and call proc.waitFor()
    I would expect to see the output of the command in the stdout stream even though the command hasn't exited. I had hoped to parse the output to determine the necessary response. However, the calls to read the contents of the stdout and stderr streams block and I never see any output.
    How can I get access to the contents of those streams while the command is still running? Is this supported through the Runtime.exec interface?
    Thanks,
    Shawn

    This article should help:
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html

  • How to run sequential commands by runtime or whatever in java?

    I'm doing a compile function in java GUI and need to run several commands one by one, how can i do this and how can i know that the previous command has been done and finished?
    commands like
    make ....
    make ....
    make ....
    then do
    ./run.x ....
    thanks a lot!

    THe Process object that Runtime.exec method returns has a method called waitFor. Calling it makes the currently executing Java thread wait for the process to exit.
    (apidoc: http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Process.html#waitFor())

  • Need to run two commands in Runtime.getRuntime.exec()???

    I need to run two commands in the same shell , in the same exec function... is this possible? I tried to invoke
    ksh -e ... command1;command2
    but that did nothing

    I need to run two commands in the same shell , in the
    same exec function... is this possible? I tried to
    invoke
    ksh -e ... command1;command2
    but that did nothingI'm not all that familiar with that particular shell (ksh), but if it works from the command-line, I'd venture to guess that it would have worked there as well. My guess is it did "work" (executed the 2 commands) but that you may have misdiagnosed the real problem (current working directory assumption incorrect, etc).

  • Need help with Runtime class in UNIX

    I am attempting to kick off a C++ executable from within java. This class is called through a UI.
    The executable runs in the form of the exec followed by name=value pairs, ie [path/exec] [n=v] [n=v] ... and runs fine from the command line.
    Examples: These don't kick it off, but don't error either.
    String cmd[] = {"/bin/sh","-c","[path]/[exec] [n=v]};
    String cmd[] = new String[3];
    cmd[0] = "[path]/[exec]";
    cmd[1] = "[n=v]";
    cmd[2] = "[n=v]";
    Process p = Runtime.getRuntime().exec(cmd);
    I'm thinking it may be an environment issue, ie env vars not set because the only way I can get this to work is to put the command in a shell script that sets the env vars and kicks off the executable. Like:
    String cmd[] = {"/bin/sh","-c","/[path]/test.sh"};
    I'd prefer to kick this off from the java code. It sounds like I need to find a way to shell out, run our script to set env vars, then kick off the exec. This is my first attempt w/ using Runtime, so maybe I'm missing something.
    Thanks in advance for the help.

    I think this sort of thing will depend upon the shell you're in. When you use Runtime.exec you (might) lose your "parent" shell's environment variables - this question shows up here now and again, here's one thread that might help:
    http://forum.java.sun.com/thread.jspa?threadID=468648&messageID=2172572
    You might find some enlightenment on Roedy's Java Glossary here: http://mindprod.com/jgloss/exec.html
    Hope that helped
    Lee

  • Run external programs using runtime class

    Okay, I'm experiencing a really annoying problem with java.lang.runtime
    I'm building a GUI that needs to run some external programs, via a button say. These generally produce a text file or something, so I don't need to stream the output or anything (at least I'm assuming I don't?). Should be very simple...
    So at the terminal (bash) I would type ./programName , and everything will run hunkey dorey.
    In my code then, natrurally, I write
    String cmd = "./programName";
    Process p = runtime.getRuntime().exec(cmd);
    But low and behold...nothing happens. What is going on here, and how do I get around it! ??
    (On windows incidentally, it's no problem at all and works absolutely fine. But when I go over to mac, which is what I need to use, I'm screwed - only adding to the annoyance!)
    Any help would be much appreciated as I have a deadline looming!!

    You need to 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 implement the recommendations. Failure to implement all the recommendations will cause you grief.
    P.S. The fragment of code you have posted shows that you have fallen for at least 4 of the traps.

  • Problem while running dos command from java program

    Dear friends,
    I need to terminate a running jar file from my java program which is running in the windows os.
    For that i have an dos command to find process id of java program and kill by using tskill command.
    Command to find process id is,
    wmic /output:ProcessList.txt process where "name='java.exe'" get commandline,processid
    This command gives the ProcessList.txt file and it contains the processid. I have to read this file to find the processid.
    when i execute this command in dos prompt, it gives the processid in the ProcessList.txt file. But when i execute the same command in java program it keeps running mode only.
    Code to run this command is,
    public class KillProcess {
         public static void main(String args[]) {
              KillProcess kProcess = new KillProcess();
              kProcess.getRunningProcess();
              kProcess = new KillProcess();
              kProcess.readProcessFile();
         public void getRunningProcess() {
              String cmd = "wmic /output:ProcessList.txt process where \"name='java.exe'\" get commandline,processid";
              try {
                   Runtime run = Runtime.getRuntime();
                   Process process = run.exec(cmd);
                   int i = process.waitFor();
                   String s = null;
                   if(i==0) {
                        BufferedReader stdInput = new BufferedReader(new
                               InputStreamReader(process.getInputStream()));
                        while ((s = stdInput.readLine()) != null) {
                         System.out.println("--> "+s);
                   } else {
                        BufferedReader stdError = new BufferedReader(new
                               InputStreamReader(process.getErrorStream()));
                        while ((s = stdError.readLine()) != null) {
                         System.out.println("====> "+ s);
                   System.out.println("Running process End....");
              } catch(Exception e) {
                   e.printStackTrace();
         public String readProcessFile() {
              System.out.println("Read Process File...");
              File file = null;
              FileInputStream fis = null;
              BufferedReader br = null;
              String pixieLoc = "";
              try {
                   file = new File("ProcessList.txt");
                   if (file.exists() && file.length() > 0) {
                        fis = new FileInputStream(file);
                        br = new BufferedReader(new InputStreamReader(fis, "UTF-16"));
                        String line;
                        while((line = br.readLine()) != null)  {
                             System.out.println(line);
                   } else {
                        System.out.println("No such file");
              } catch (Exception e) {
                   e.printStackTrace();
              return pixieLoc;
    }     when i remove the process.waitFor(), then while reading the ProcessList.txt file, it says "No such file".
    if i give process.waitFor(), then it's in running mode and program is not completed.
    Colud anyone please tell me how to handle this situation?
    or Is there anyother way to kill the one running process in windows from java program?
    Thanks in advance,
    Sathish

    Hi masijade,
    The modified code is,
    class StreamGobbler extends Thread
        InputStream is;
        String type;
        StreamGobbler(InputStream is, String type)
            this.is = is;
            this.type = type;
        public void run()
            try
                InputStreamReader isr = new InputStreamReader(is, "UTF-16");
                BufferedReader br = new BufferedReader(isr);
                String line=null;
                while ( (line = br.readLine()) != null)
                    System.out.println(type + ">" + line);
                } catch (IOException ioe)
                    ioe.printStackTrace(); 
    public class GoodWindowsExec
        public static void main(String args[])
            try
                String osName = System.getProperty("os.name" );
                String[] cmd = new String[3];
                 if( osName.equals( "Windows 95" ) )
                    cmd[0] = "command.com" ;
                    cmd[1] = "/C" ;
                    cmd[2] = "wmic process where \"name='java.exe'\" get commandline,processid";
                } else {
                    cmd[0] = "cmd.exe" ;
                    cmd[1] = "/C" ;
                    cmd[2] = "wmic process where \"name='java.exe'\" get commandline,processid";
                Runtime rt = Runtime.getRuntime();
                System.out.println("Execing " + cmd[0] + " " + cmd[1]
                                   + " " + cmd[2]);
                Process proc = rt.exec(cmd);
                System.out.println("Executing.......");
                // any error message?
                StreamGobbler errorGobbler = new
                    StreamGobbler(proc.getErrorStream(), "ERROR");           
                          // any output?
              StreamGobbler outputGobbler = new
                    StreamGobbler(proc.getInputStream(), "OUTPUT");
                          // kick them off
                errorGobbler.start();
                outputGobbler.start();
                // any error???
                int exitVal = proc.waitFor();
                System.out.println("ExitValue: " + exitVal);       
            } catch (Throwable t)
                t.printStackTrace();
    }when i execute the above code, i got output as,
    Execing cmd.exe /C wmic process where "name='java.exe'" get commandline,processid
    and keeps in running mode only.
    If i execute the same command in dos prompt,
    CommandLine
    ProcessId
    java -classpath ./../lib/StartApp.jar;./../lib; com.abc.middle.startapp.StartAPP  2468
    If i modify the command as,
    cmd.exe /C wmic process where "name='java.exe'" get commandline,processid  > 123.txt
    and keeps in running mode only.
    If i open the file when program in running mode, no contents in that file.
    If i terminte the program and if i open the file, then i find the processid in that file.
    Can you help me to solve this issue?

  • Can use STSongStd-Light-Acro.otf font in unix system(aix)

    In unix system (aix 5.3)
    as 10.1.2
    NLS_LANG=AMERICAN_AMERICA.ZHS16GBK (chinese charater)
    Now run report, output charaters is not right,why?
    In windows system,I modify uifont.ali file,as the follow
    [ PDF ]
    .....ZHS16GBK = "STSongStd-Light-Acro"
    and the report run well,but the same config in unix system (aix 5.3),output charaters is error.
    why?
    Can anyone tell me step by step?
    Thanks in advance!

    Welcome to OTN
    Check the two link..
    1. Re: Oracle Reports 10g Fonts issue
    2. Re: Adding new font to my Reports Setup
    Hope this will help you
    Hamid
    If someone's response is helpful or correct, please mark it accordingly.

  • Running System commands using Runtime.exec()

    I'm trying to run an example from "The Java Programming Language" book by Arnold, Gosling and Holmes. I'm trying to run a system level command and get the results. The code looks like:
    public static String[] runCommand(String cmd) {
    String[] outputData= null;
    String[] cmdArray = {"/usr/bin/ls", "-l", "/tmp"};
    try {
    Process child = Runtime.getRuntime().exec(cmdArray);
    InputStream in = child.getInputStream();
    InputStreamReader reader = new InputStreamReader(output);
    BufferedReader = new BufferedReader(reader);
    // read the commands output
    int counter = 0;
    String line;
    while ((line = input.readLine()) != null)
    outputData[counter++]= line;
    if (child.waitFor() != 0){  // error when it's not 0       
    System.out.println("Couldn't run the command.");
    System.out.println("It produced the following error message : " + child.exitValue());
    outputData = null;
    } catch (Exception e){
    System.out.println("It got here!");
    System.out.println("It produced the following error message : " + e.getMessage());
    outputData = null;
    return outputData;
    It gets to the while line, trys to run the input.readLine() and kicks out the exception that looks like:
    It got here!
    It produced the following error message : null
    I know it gets to the input.readLine() because I had a whole lot more try blocks in there, but for simplicity left it out (so it look like the code in the book, which I tried originally). When I run the same command from the command line (on our Sun Solaris 2.8 system) I get results back. I'm not sure what I'm doing wrong. Any help would be greatly appreciated. Thanks.

    Hi, duffymo, hope you can help me. Consider this servlet code:
    String theCommand = "csh /export/home/gls03/sasstuff/runsas.csh /export/home/g
    ls03/sasstuff/gary2.sas";
    //Create a parent Process for the sas program subprocess:
    Process p = rt.exec(theCommand);
    System.out.println("after call to rt.exec(theCommand)");
    Here is the runsas.csh script:
    #!/bin/csh
    setenv LD_LIBRARY_PATH /opt/sybase/lib:/usr/lib:/usr/openwin/lib:/opt/SUNWspro/S
    C2.0.1
    setenv SASROOT /usr/local/CDC/SAS_8.2
    setenv XKEYSYMDB /usr/local/CDC/SAS_8.2/X11/resource_files/XKeysymDB
    $SASROOT/sas -sasuser /hpnpages/cgi-bin/applinks/hospcap/tmp $1
    The execution never gets to the println statment, here is the error:
    class java.io.IOException Exception. Message: CreateProcess: csh /export/home/g
    ls03/sasstuff/runsas.csh /export/home/gls03/sasstuff/gary2.sas error=2
    java.io.IOException: CreateProcess: csh /export/home/gls03/sasstuff/runsas.csh /
    export/home/gls03/sasstuff/gary2.sas error=2
    at java.lang.Win32Process.create(Native Method)
    at java.lang.Win32Process.<init>(Win32Process.java:66)
    at java.lang.Runtime.execInternal(Native Method)
    at java.lang.Runtime.exec(Runtime.java:551)
    at java.lang.Runtime.exec(Runtime.java:477)
    at java.lang.Runtime.exec(Runtime.java:443)
    at sasRunnerNew.doPost(sasRunnerNew.java:103)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:760)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubIm
    pl.java:262)
    at weblogic.servlet.internal.TailFilter.doFilter(TailFilter.java:21)
    at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.ja
    va:27)
    at us.ny.state.health.hin.hinutil.HinFilter.doFilter(HinFilter.java:124)
    at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.ja
    va:27)
    at weblogic.servlet.internal.WebAppServletContext.invokeServlet(WebAppSe
    rvletContext.java:2643)
    at weblogic.servlet.internal.ServletRequestImpl.execute(ServletRequestIm
    pl.java:2359)
    at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:139)
    at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:120)
    The command runs fine in unix.
    I've also tried using these as arguments to exec:
    String theCommand = "/bin/csh /export/home/gls03/sasstuff/runsas.csh /export/home/gls03/sasstuff/gary2.sas";
    String[] theCommand = {"csh", "/export/home/gls03/sasstuff/runsas.csh", "/export/home/gls03/sasstuff/gary2.sas"};
    These generate the same error. I'm thinking this is a sas-specific problem.
    Thanks for any help. Gary

  • Run Host Command on UNIX

    Hi,
    We use JAVA source in Oracle to execute some unix commands directly from within stored procedures in Oracle.
    Our Java source looks like this :
    CREATE OR REPLACE AND RESOLVE JAVA SOURCE NAMED "HOST" AS
    import java.lang.*;
    import java.io.*;
    public class Host
    public static void executeCommand (String command, String etype) throws IOException
    String[] wFullCommand = {"C:\\winnt\\system32\\cmd.exe", "/y", "/c", command};
    String[] uFullCommand = {"/bin/sh", "-c", command};
    if (etype.toUpperCase().equals("W"))
    Runtime.getRuntime().exec(wFullCommand);
    else if(etype.toUpperCase().equals("U+"))
    Runtime.getRuntime().exec(uFullCommand);
    else if(etype.toUpperCase().equals("U"))
    Runtime.getRuntime().exec(command);
    CREATE OR REPLACE PROCEDURE Host_Command (p_command IN VARCHAR2, p_etype IN VARCHAR2)
    AS LANGUAGE JAVA
    NAME 'Host.executeCommand (java.lang.String, java.lang.String)';
    We call one unix shell script and discover that some UNIX commands from this shell script are executed and others not. A cp & touch command don't give problems whilst cat & unix2dos commands don't function.
    Can anybody help me on this subject?
    Thanks !
    Kris

    Hi Avi, thanks for your reaction. Got it to work with the unix scripts, the problem was a syntax error in the script itself.
    However I don't get it to function when I try to run a unix command directly. Normally the parameter U+ should decide to start it in a shell for scripts and otherwise it should run the command directly. (whithout the /bin/sh in front of it).
    I already adapted my source to try to execute the command in a new shell but without success :
    String[] uFullCommand = {"/bin/sh", "-c", "\'cp /export/home/caluwaek/test/bestand2 /export/home/caluwaek/test/bestand8\'"};
    I tried to put the whole command in one string, in 3 strings, to just call the cp command without bothering the shell. Nothing seems to work.
    In unix both the following work :
    cp /export/home/caluwaek/test/bestand2 /export/home/caluwaek/test/bestand8
    and
    /bin/sh -c 'cp /export/home/caluwaek/test/bestand2 /export/home/caluwaek/test/bestand8'
    Thanks for your help!
    Kris

  • Error while Executing Unix Shell Commands Using Runtime clas

    I am trying to run the following code in java on unix machine to execute cat command.
    Runtime runtime = Runtime.getRuntime();
              try {
                   System.out.println("before catexecute");
                   Process process = runtime.exec("cat /export/home/shankerr/local.profile > /export/home/shankerr/local1.txt");
                   try {
                        if (process.waitFor() != 0) {
                        System.err.println("exit value = " +
                                  process.exitValue());
                        catch (InterruptedException e) {
                        System.err.println(e);
    But i get the following error on the console
    exit value = 2
    cat: cannot open >
    cat: cannot open /export/home/shankerr/local1.txt
    The same command if i run on unix console directly it creates a new file and copies the content into the new file local1.txt
    kindly help me on the same

    The redirection operator > along with stuff like pipe | history !$ etc. is interpreted by the shell, not by the cat program.
    When you do cat X > Ycat only sees the X. The rest is interpreted by the shell to redirect the cat program's stdout.
    However, when you Runtime.exec(), you don't have the shell, so cat sees X > Y as its arguments, and interprets them all as file names. Since there's no file named > you get the error.
    The solution is to first man cat on your system and see if it happens to have a -o or somesuch operator that lets it (rather than the shell) send its output to a file. If not, then you need to invoke a shell, and pass it cat and all of cat's args as the command to execute.
    Read the man pages for you shell of choice, but for bash, I believe you'd give Runtime.exec() something like /bin/bash -c 'cat X > Y'

  • Encountering a RunTime error when I try running from command prompt

    When I try to load my class from the command prompt I get the error:
    Exception in thread "main" java.lang.NoClassDefFoundError: MiniTriangle
    Since this seems like a pretty basic error, I'm hoping there's a black and white solution to it. Unfortunatly I don't have the slightest idea what that might be.
    Any help would be appreciated, thanks in advance!!!

    I'm pretty new to this myself but have encountered this error before. I've found it happens when you try to run the programme and the class name isn't the same as the file name. So if you named the text file when you wrote the code MiniTriangle when you compile it you will get a file called MiniTriangle.class which is what you are trying to run. However if you inadvertently misspelled the class definition in the code and entered say
    class MiniTringle {
    you would get the error you are experiencing when you try to run MiniTriangle.class
    Hope this helps

  • To run an application on iAS6sp1 on HP-Unix, while starting the kjs from command line, it gives a GDS error and crashes. Subsequently, after stopping all services and restarting iAS wouldnot come up.

     

    Hi,
    Not a problem, please post the KJS error logs for me to hunt the
    exact reason for the error.
    Thanks & Regards
    Raj
    Neel John wrote:
    To run an application on iAS6sp1 on HP-Unix, while starting the kjs
    from command line, it gives a GDS error and crashes. Subsequently,
    after stopping all services and restarting iAS wouldnot come up.
    Try our New Web Based Forum at http://softwareforum.sun.com
    Includes Access to our Product Knowledge Base!

  • Unable to run Java Command (on UNIX)

    Hi,
    When I try to run Java command:
    java ChatServer 9830
    I get the following error:
    /usr/bin/java: line 67: /tmp/javaJb9694: Permission denied
    /usr/bin/java: line 67: /tmp/javaJb9694: Success
    Could any one suggest what could be the reason and solution.
    The site is hosted on a UNIX palatform and we are using Tomcat.
    Thanks & Regards,
    Joy.

    lol
    How would we know? We don't know your setup, we don't know your software, we don't know what happens...
    It doesn't even look like a standard Java message to me.

Maybe you are looking for

  • Mac Keyboard Functions Don't Work

    I have just discovered that the Mac keyboard has a very useful feature: press and hold a key and all the options for that character show in a little pop-up window, i.e., accents, tilde's, etc. This works in all my other programs (Word, Excel, Pages,

  • Java all messed up after SL install

    I'm having trouble with Java on both Firefox and Safari after a snow leopard install, and cannot find anything out about it online to fix it. Firefox This issue isn't causing me as many issues. When I log into WebVista (a board for the University of

  • Tools to upload data into SRM 7.0 with webdynpro for ABAP

    Hi, Webdynpro for abap is used in SRM70. I need to load data in SRM70 (product category...). ECATT is not working with web dynpro for abap. What other tools can i use to load data in SRM70 ? LSMW ? I would like to avoid to create a Z program to load

  • In mac OS, embedding ms word inside a SWT frame.

    i wan't to embed microsoft word inside SWT or java frame in macintosh OS. In windows OS, i embedded ms word inside a frame using org.eclipse.SWT.ole.win32 package. But in macintosh OS, i want to know the swt class or alternative GUI toolkit to embed

  • Specified anchor not found in the model in SAP Records Management

    Hi Experts, We are on SRM 7.0 SP 8 PPS with ECC 6.0 Ehp 4  with RM. I have managed to Integrate SRM with RM with some issues. The issues are: RFx with attachment is not displayed in RM through related links. Whereas RFx without attachments are visibl