Java.lang.Runtime.exec problem in ubuntu 9.10

Hi:
I tried to run some command in the java code , for example "grass64 -text /home/data/location", this command works well in the terminal, however when I call it in the java code I got some excepetions.
My code is :
public class Grass {
     public static String grassBatJob="GRASS_BATCH_JOB";
     public void run(String cmd,String jobPath) {
          //set the environments variables
          Map<String, String> env=new HashMap<String, String>();
          env.put(grassBatJob, jobPath);
          String gisDataBase="/home/kk/grass/GrassDataBase";
          String location="spearfish60";
          String mapset="PERMANENT";
          cmd=cmd+" "+gisDataBase+"/"+location+"/"+mapset;
          CommandLine line=new CommandLine(cmd);
          //the real cmd should be >>grass64 -text /home/kk/grass/GrassDataBase/spearfish60/PERMANENT
          System.out.println("start line=="+line.toString());
          DefaultExecutor de=new DefaultExecutor();
          try {
               int index=de.execute(line,env);
               System.out.println(index);
          } catch (ExecuteException e) {
               e.printStackTrace();
          } catch (IOException e) {
               e.printStackTrace();
     public static void main(String[] args) {
          String jobPath=Grass.class.getResource("grass.sh").getFile();
          new Grass().run("grass64 -text", jobPath);
The real cmd I want to execute is "grass64 -text /home/kk/grass/GrassDataBase/spearfish60/PERMANENT" with the envrionment variable "GRASS_BATCH_JOB=jobPath",it works well in the ternimal ,however in my application I got the exception"
java.io.IOException: Cannot run program "grass64 -text /home/kk/grass/GrassDataBase/spearfish60/PERMANENT": java.io.IOException: error=2, No such file or directory
     at java.lang.ProcessBuilder.start(ProcessBuilder.java:459)
     at java.lang.Runtime.exec(Runtime.java:593)
     at org.apache.commons.exec.launcher.Java13CommandLauncher.exec(Java13CommandLauncher.java:58)
     at org.apache.commons.exec.DefaultExecutor.launch(DefaultExecutor.java:246)
     at org.apache.commons.exec.DefaultExecutor.executeInternal(DefaultExecutor.java:302)
     at org.apache.commons.exec.DefaultExecutor.execute(DefaultExecutor.java:149)
     at org.kingxip.Grass.run(Grass.java:27)
     at org.kingxip.Grass.main(Grass.java:38)
Caused by: java.io.IOException: java.io.IOException: error=2, No such file or directory
     at java.lang.UNIXProcess.<init>(UNIXProcess.java:148)
     at java.lang.ProcessImpl.start(ProcessImpl.java:65)
     at java.lang.ProcessBuilder.start(ProcessBuilder.java:452)
     ... 7 more
I wonder why?

Thanks for all of your reply, and now I can run the command, however I met some problems when I tried to get the result of the exec.
The core codes are shown below:
String cmd="g.version";
String[] exe={"bash","-c",cmd};
Process p1=Runtime.getRuntime.exec(exe,env); // the env has been set
GrassThread outThread=new GrassThread("out", p1.getInputStream());
outThread.start();
GrassThread errorThread=new GrassThread("error", p1.getErrorStream());
errorThread.start();
int exitVal = p1.waitFor();
String resu=outThread.sb.toString();
System.out.println("==========the output start========");
System.out.println(resu);
System.out.println("==========the output end========");
System.out.println("ExitValue: " + exitVal); //------------------> line one
public class GrassThread extends Thread{
     public StringBuffer sb=new StringBuffer();
     public GrassThread(String type,InputStream is) {
          this.type=type;
          this.is=is;
     public void run() {
          try {
               InputStreamReader isr = new InputStreamReader(is);
               BufferedReader br = new BufferedReader(isr);
               String line = null;
               while ((line = br.readLine()) != null) {
                    System.out.println(type + ">" + line);
                    sb.append(line).append("\r");  // ----------------------------> line two
}I define a StringBuffer in the GrassThread to save the output (see the code where I marked by "line two"), and when the process complete, I check the StringBuffer to get the output (see code where I marked by "line one"), however the output in the console of the IDE are :
----------- output in the console of the IDE start -------------
==========the output start========
==========the output end========
ExitValue: 0
out>GRASS 6.4.0RC5 (2009)
----------output in the console of the IDE end--------------------
I can not understand, in the code "line one", I first get the output using "System.out.println(resu);",then I print the exitvalue,but why the order of the output in the console is not what I expected?
Another question, the code above assume the output can be got from the Process's getInputStream, however sometimes the output maybe come from the Process's getErrorStream, so how to handle it?
Edited by: apachemaven on 2010-3-5 ??5:38

Similar Messages

  • Java.lang.Runtime.exec()

    When using the exec method I cannot get it to run the specified application when I try to use the Runtime.execString[] cmdArray)
    The application I am running is windump, it runs ok when I specify it in the Runtime.exec(String cmd) method.
    I need to use the Runtime.exec(String[] cmdArray) option as I need to specify parameters as part of my project. To be exact I need to tell it to output to a text file.
    I can do this when running windump from the command prompt, thus cannot understand whty it wont work when I specify the same option from Runtime.exec(..)
    Any ideas how to overcome this?
    thanks Conor

    This works for me on WindowsNT:
    try {
         Runtime.getRuntime().exec("cmd.exe /c dir>dirtest.txt");
    catch (Exception e) {}
    [/code}
    Mark

  • Java.lang.Runtime.exec() again

    try{
    Process registryProcess = null;
    Runtime r = Runtime.getRuntime();
    String[] cmdArray = {"F:\\windump", ">>new_res.txt"};
    registryProcess = r.exec(cmdArray);
    }catch(Exception ex){
    System.out.println("Exception Caught: " + ex.getMessage());
    ** Have also tried speicfying the command and the parameters all in the one string like so :
    String cmd = "F:\\windump >>F:\\new_res.txt";
    registryProcess = r.exec(cmd);

    try
    String cmd = "cmd /c F:\\windump >> F:\\new_res.txt";
    registryProcess = r.exec(cmd);

  • Invoke exe through java code(using java.lang.Runtime)

    Iam trying to invoke an exe from java code.If i give the complete path for that exe it is running fine .But if i set the environment variable and directly execute the exe through command prompt it iss running fine , but it fails to run when i do the same using java code i.e. java.lang.Runtime.exec function

    Give "//" for directory seperator.
    E.g. r.exec("c://test//test.exe",null);
    Why? That doesn't look correct.It is correct. It will work fine. Try it out.But it doesn't add or solve anything. A forward slash
    does not need to be escaped.'
    It's not even escaping. It's just doubling up. If that works, I'd bet "C://///test///////test.exe" does also.

  • Java.lang.Process.exec()

    I have read a article about the "java.lang.Process.exec()" (url:http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html)
    Having some questions with the example in it.
    The example code:
    import java.util.*;
    import java.io.*;
    public class BadExecJavac
        public static void main(String args[])
            try
                Runtime rt = Runtime.getRuntime();
                Process proc = rt.exec("javac");
                //int exitVal = proc.exitValue();
                int exitVal = proc.waitFor();
                System.out.println("Process exitValue: " + exitVal);
            } catch (Throwable t)
                t.printStackTrace();
    }The process can run but never complete.
    Why? Just because when invoke the javac.exe without any argument,it will product a set of usage statements that describe how to run the program and the meaning of all the available program options.So the process is in deadlock.
    The question is, when i change the exec("javac") to exec("javac a.java"), in which the "a.java" is not exist, so the jvm should product error:
    error: cannot read: a.java
    1 error
    But after i changed the code and run the class, at this time the process can run and complete.
    The two codes both product some statements,but why the first one never complete,but the second did. Why?

    import java.util.*;
    import java.io.*;
    public class A
        public static void main(String args[])
            try
                Runtime rt = Runtime.getRuntime();
                Process proc = rt.exec("javac");
                InputStream is = proc.getErrorStream();
                int i=0;
                while ((i = is.read()) != -1)
                    System.out.print((char)i);
                // int exitVal = proc.exitValue();
                // int exitVal = proc.waitFor();
                // System.out.println("Process exitValue: " + exitVal);
            } catch (Throwable t)
                t.printStackTrace();
    }usng this modification, i could see some error messages.
    because exec(cmd) executes the command in a separate process, it will not display the results on the current console. If you want see the results, you should use getInputStream() and getErrorStream().
    good luch ^^

  • Java's Runtime.exec() method

    When you shell out to java's Runtime.exec() method, are the process name and arguments the same for the child process that is spawned.
    We see duplicated processes about the time when our logs tell us this command was run. However, we cannot seem to reproduce this. Has anyone else seen anyone this before?

    That's what I though too. But check this out . . .
    Our code looks as follows:
    private Runtime rt;
    private Process p;
    rt = Rutime.getRuntime();
    p = rt.exec(command);
    This exec() call creates a new process, which is a child of the java process that runs this command. The final process looks like the "command" string that is passed to the exec() method call. In our case, the command is a call to the /usr/bin/mail utility to send out faxes and emails.
    We ran a very tight loop executing the rt.exec() call over and over. What we found was that for a minor fraction of a second, the newly created process looks just like the original process including the same arguments. However, the PID's indicated that one process was the child of the other. This is why it looked like we had 2 of the same processes. WILD!
    Thanks guys!

  • Hi java.lang.System.gc() vs java.lang.Runtime.gc()

    hi all what is the exact diff.,
    java.lang.System.gc() vs java.lang.Runtime.gc()
    why dont I call Runtime.gc() like System.gc(), is ther any possibility ?
    Thanks in advance

    Thanks, but I just want to call Runtime.gc() like
    System.gc() forcefully to invoke finalize() method
    Thanks in advanceThe calls are the same. Read the javadoc:
    http://java.sun.com/j2se/1.5.0/docs/api/java/lang/System.html#gc()
    public static void gc()
    Runs the garbage collector.
    Calling the gc method suggests that the Java Virtual Machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse. When control returns from the method call, the Java Virtual Machine has made a best effort to reclaim space from all discarded objects.
    The call System.gc() is effectively equivalent to the call:
    Runtime.getRuntime().gc()

  • Java/lang/Runtime exception

    java.lang.RuntimeException: IOException reading reader invalid byte 1110011 error caused while running sun Wireless tool kit.Can any body please help me to solve this problem. I am using Eclipse 3.3 and also eclipse 3.2
    with sun java wireless toolkit in ubuntu.
    Thanks and Regards,
    Pandian

    Support for the RecipeFox extension is over here: <br />
    http://recipetools.sourceforge.net/phpBB3/index.php

  • Java.lang.NoSuchMethodError JAR problem

    Hi
    Running on Pocket PC using IBMs j9.
    If we build Jar A with a different library Jar B where a method in a class in A refers to a method in a class in B we get java.lang.NoSuchMethodError at runtime. Despite the fact that in jar B the Class and it's methods have not changed.
    This is worrying. Anybody got an explanation?
    Many thanks
    Ged
    a copy of any comment to [email protected] would be appreciated

    Hi
    Both jars are our own libraries. If we compare a calling jar (A) compiled against different called jars (B) then they are different !*@???
    I agree that one might expect that it is finding another implementation on the class path that is missing the method but I haven't found anything . The environment is an XDA 2 so it is limited.
    To add insult to injury we seem to have found another, different instance of the problem today.
    I must admit that I feel that we are missing something (brains ?).
    Cheers
    Ged

  • Invoke RealVNC using java code(java.lang.Runtime)

    I would like to invoke vncviewer exe whenever user presses a button.Please help

    What part are you having trouble with? What have you done so far?
    Note that you have two main problems to solve here.
    Do you know how to perform a given action when a button is pressed? If not, google for a swing tutorial. You'll want some kind of Listener, though I don't know the specific class name.
    Do you know how to invoke another executable program from within a Java app? If not, look into Runtime.exec.

  • Runtime.exec--problems writing to external file

    Hi. I went to http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html, and am still quite confused regarding the use of Runtime.exec, for my purposes. I want to decompile a CLASS file using javap, and then write that to a TXT file, for easier reading/input to JAVA. Now, I use the following code (a modification of what I got from http://www.mountainstorm.com/publications/javazine.html, as the "traps" article's sample code is WAY too confusing--they say the compiler had the output sent to text.txt, without even showing how in the source code they did that), but it hangs up. Modifications to the string array cause different results, such as showing the javap help menu, or saying that the class wasn't found, but I think the way I did the array here is right:
    import java.util.*;
    import java.io.*;
    public class Test {
            try {
             String ls_str;
                String[] cmd = {"C:\\j2sdk1.4.2_04\\bin\\javap", "-c", "-classpath", "H:\\Java\\metricTest", "metricTest > blah.txt", ""};
                Process ls_proc = Runtime.getRuntime().exec(cmd);
             // get its output (your input) stream
             DataInputStream ls_in = new DataInputStream(
                                              ls_proc.getInputStream());
             try {
              while ((ls_str = ls_in.readLine()) != null) {
                  System.out.println(ls_str);
             } catch (IOException e) {
              System.exit(0);
         } catch (IOException e1) {
             System.err.println(e1);
             System.exit(1);
         System.exit(0);
    }

    Also, jesie, I realize that's what I need...the only
    problem is, the name "test.txt" is nowhere to be found
    in the source code! lolLooks like I have to explain this, then.
    When you look at a Java program you'll notice that it always has a "main" method whose signature looks like this:public static void main(String[] args)When you execute that program from the command line, it takes whatever strings you put after the class name and passes them to the main program as that array of strings. For example if you run it likejava UselessProgram foo bar hippothen the "java" command takes the three strings "foo", "bar", and "hippo" and puts them into that args[] array before calling the "main" method.
    That means that inside the "main" method in this case, "args[0]" contains "foo", "args[1]" contains "bar", and "args[2]" contains "hippo".
    Now go back to the example and see how it lines up with that.

  • Runtime exec problem with command "start"

    L.S,
    I'm working on a webservice client for uploading
    and downloading files. When a file is downloaded, it
    should be opened by the appropriate application. I
    know that this is -in theory- possible by issuing a
    start command through Runtime.getRuntime.exec():
    public void doSomething(String realName, DataHandler handler) {
      File outFile = new File(realName);
      FileOutputStream out = new FileOutputStream(outFile);
      handler.writeTo(out);
      out.close();
      String fileName = outFile.getAbsolutePath();
      Process p = Runtime.getRuntime().exec("start " + fileName);
    }Running this on my Win2000 system with J2RE 1.4.2 consistently
    fails with this message:
    java.io.IOException: CreateProcess: start C:\tmp\test.pdf error=2When I issue the exact same command from a DOS shell, Adobe
    starts up with the test document loaded. I now believe that my own
    application is somehow 'holding on to' the file, preventing an
    external application like Adobe from consuming the same file.
    Does anyone know how I can get around a problem like this? How do
    I start the appropriate application and feed it the file that was
    just downloaded by the user?

    I did a search for Runtime.exec and found some good help in this forum. Someone posted something like the following and it works pretty well.
    <<begin code>
    // Determine proper shell command (extend per OS)
    String os_name = System.getProperty("os.name");
    String shellParam "";
    if (os_name.startsWith("Windows"))
    if ( (System.getProperty("os.name").endsWith("NT")) ||
    (System.getProperty("os.name").endsWith("2000")) ||
    (System.getProperty("os.name").endsWith("XP")) )
    shell = "cmd.exe";
    } else
    shell = "command.com";
    shellParam = "/C";
    // Create a string with your program executable
    String command = "myprogram.exe";
    // Create an array of each command, I found that placing "cmd.exe /c"
    // in the same string doesn't work.
    String[] cmd_array = new String[] {
    shell,
    shellParam,
    command
    Runtime.getRuntime().exec( cmd_array );
    <<end code>>
    Do a java API search for Runtime.exec (if you use Eclipse right click and hit Open Declaration) there are ways to invoke exec that support setting of the environment as well as the current directory.

  • Runtime.exec() problem with Linux

    Hi All,
    I have a java program which I am using to launch java programs on all platforms.
    I am using the Runtime.exec() method to start the process in a separate JVM.
    But, I had a problem with the -classpath switch if the directories contained spaces. So I modified the java command which I am passing to the exec() method to something like:
    java -classpath \"./my dir with spaces\" com.harshal.MainThis I had to do because of the problem in windows. But, if I use double quotes in Linux (for the classpath switch in my exec() method), it won't work.
    Can anyone correct me so that I can use the Runtime.exec() method on all platforms to launch the java application even if the classpath directories contains spaces.
    Thank you very much.

    I was reading about the command line args on java's
    tutorial and I found a shocking news. Mac OS doesn't
    support command line args, That's news to me. Could you please elaborate ?
    More important is: I got it working. I figured out I had forgotten to try something before, or, to be more correct, I made an error when trying malcommc's envp suggestion: I used "classpath" as key, not "CLASSPATH", as it should have been.
    Ran a new test, got it working.
    Sample:
    Given a rootdir. Subdirectory "cp test" with a classfile (named "test") without package declaration. Running another class in another directory, using:
    String[] cmd = new String[]{
        "java", "test"
    String[] envp = new String[]{
        "CLASSPATH=rootdir:rootdir/cp test" // <-- without quotes.
    Runtime.getRuntime().exec(cmd, envp);It's been my wrong all the time. I didn't check hard enough. It simply had to work somehow (that's the kind of things that's easy to say afterwards :-)).

  • Runtime exec problem to execute a C program

    Hi,
    I've spend lot of time trying to find a solution without success...
    My aim is to run a C program from a java application under linux. My C code is the following:
    #include <stdlib.h>
    #include <stdio.h>
    #include <string.h>
    main(int argc, char **argv){
    printf("hello world \n");
    Once compiled I run my java application wich run the binary through a runtime.exec().
    I followed the example given by
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
    with the same input gobblers and threads.
    For some reason it doesn't work: nothing comes out...
    When I call "ls" instead of my binary it works perfectly!
    WHY??
    Any help would be greatly appreciated!

    Thanks for the reply.
    Yes it seems that JNI could be a solution, but it looks a bit complicated an maybe not so well adapted to my purpose.
    The executables I want to execute from my java application don't need any arguments.
    If JNI is really the only way I'll try to use it but is there any good reason why runtime exec doesn't work? It is supposed to execute any executable isn't it?
    cheers

  • Runtime.exec  problems

    Hi
    I would like to open a chm file from my "help" menu.
    I got two problem related to that:
    1.The first time the menu is clicked i start the process and the help is opened on top of my application frame.
    but - the second time It is opened - the only wat to recognize i sthe process is still active is to call exitValue (if it get an exception - process is still active) but - how can i make the frame on top of my application frame( the current active frame)
    2.when the application is closed the help application does not "die" with the rest of the application.
    I will be happy to get some ideas of how can i control it.
    this is my code:
    Runtime runtime=  Runtime.getRuntime();
            try {
                if(process==null){
                     process=runtime.exec(new String[] {"cmd.exe","/c" , helpLink});
                else{
                    try {
                        process.exitValue();
                        process = runtime.exec(new String[]{"cmd.exe", "/c", helpLink});
                        if (log.isDebugEnabled())
                            log.debug("process finish working");
                    } catch (IllegalThreadStateException e1) {
                        if (log.isDebugEnabled())
                            log.debug("process still working");
            } catch (IOException e1) {
                if (log.isErrorEnabled()){
                    log.error("could not open help file"+ helpLink);
                    log.error("exception:",e1);
                WorkingAreaManager.getWorkingAreaManagerInstance().displayErrorMessage(COULD_OPEN_HELP);
            }thanks,Liat

    1.The first time the menu is clicked i start the
    process and the help is opened on top of my
    application frame.
    but - the second time It is opened - the only wat to
    recognize i sthe process is still active is to call
    exitValue (if it get an exception - process is still
    active) but - how can i make the frame on top of my
    application frame( the current active frame)Sorry I don't know the answer to that. What happens if you invoke it a second time... does it bring up a completely new frame?
    2.when the application is closed the help application
    does not "die" with the rest of the application.
    I will be happy to get some ideas of how can i
    control it.process.destroy()?

Maybe you are looking for

  • Keeping a simple server open/listening for more than one connection

    Can someone please help me with a problem I am having. I'm running a server that accepts requests and processes data from a client. This program works FINE for one connection but as soon as I send the info to the server the connection closes and I ha

  • Printing from iPad 2 to Canon MG6120 Pixma Printer

    Hi There Apple Community, I'm trying to help out my Mother-In-Law (who I like) and I'm trying to make it as easy as possible for her to print from her iPad 2 to her Wi-Fi-enabled printer. It's like this: I'm trying to print from an iPad 2 to a Canon

  • Parsing html to text

    Im looking for a libary which can remove all tags from a html document. Ie, ending up with the 'content' of the html doc. Anyone knows of such a libary or has some example code on doing it?

  • Error while installing Forms Dev. 11gR2(Version 11.1.2.0.0) on Windows8

    Hi all! In configuration stage of installation time it's showing following error. 1. http://img69.imageshack.us/img69/9789/error1ah.png 2. http://img195.imageshack.us/img195/4789/error2kx.png please help someone.

  • Vertical line and missing quotation marks

    I am a new user to FlashPaper. When I created by PDF from Microsoft Word, a black vertical line appeared and my quotation marks disappeared. What happened? What am I doing wrong?