How to execute Linux command from Java app.

Hi all,
Could anyone show me how to execute Linux command from Java app. For example, I have the need to execute the "ls" command from my Java app (which is running on the Linux machine), how should I write the codes?
Thanks a lot,

You can use "built-in" shell commands, you just need to invoke the shell and tell it to run the command. See the -c switch in the man page for your shell. But, "ls" isn't built-in anyays.
If you use exec, you will want to set the directory with the dir argument to exec, or add it to the command or cmdarray. See the API for the variants of java.lang.Runtime.exec(). (If you're invoking it repeatedly, you can most likely modify a cmdarray more efficiently than having exec() decompose your command).
You will also definitely want to save the returned Process and read the output from it (possibly stderr too and get an exit status). See API for java.lang.Process. Here's an example
java.io.BufferedReader br =
new java.io.BufferedReader(new java.io.InputStreamReader(
Runtime.getRuntime().exec ("/sbin/ifconfig ppp0").
getInputStream()));
while ((s = br.readLine()) != null) {...                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

Similar Messages

  • Execute linux command from java

    I wanna execute linux command from java, bu the output has error:
    Return code = 1
    top: failed tty get
    The code as:
    import java.io.*;
    public class Execute {
         public static void main(String[] args) {
              try {
                   final Process process = Runtime.getRuntime().exec("top");
                   new Thread() {
                        public void run() {
                             try {
                                  InputStream is = process.getInputStream();
                                  byte[] buffer = new byte[1024];
                                  for (int count = 0; (count = is.read(buffer)) >= 0;) {
                                       System.out.write(buffer, 0, count);
                             } catch (Exception e) {
                                  e.printStackTrace();
                   }.start();
                   new Thread() {
                        public void run() {
                             try {
                                  InputStream is = process.getErrorStream();
                                  byte[] buffer = new byte[1024];
                                  for (int count = 0; (count = is.read(buffer)) >= 0;) {
                                       System.err.write(buffer, 0, count);
                             } catch (Exception e) {
                                  e.printStackTrace();
                   }.start();
                   int returnCode = process.waitFor();
                   System.out.println("Return code = " + returnCode);
              } catch (Exception e) {
                   e.printStackTrace();
    }Help please.

    Your code is probably good to run a program, that does not use terminal capabilities.
    Program "top" is a little bit more complicated - you have to run it with a real terminal.
    Try to run "xterm -e top". You can find an example how to run an external program
    from java code in cnd/gdb module on http://cnd.netbeans.org
    For example, take a look at openExternalProgramIOWindow() method on this page:
    http://cnd.netbeans.org/source/browse/cnd/gdb/src/org/netbeans/modules/cnd/debugger/gdb/proxy/Attic/GdbProxyCL.java?rev=1.1.2.6.2.5&only_with_tag=release551_fixes&view=markup
    It runs a command with external terminal.
    Thanks,
    Nik

  • Unable to execute Linux command from Java

    Hi,
    I am currently working on a code wherein i need to execute Linux command from Java. Below are some of the query i have.
    1) Is there any efficient method of running OS commands from Java, rather than using Runtime and Process method.
    2) Below is details of my code which fails in execution
    **-- Java Version**
    java version "1.6.0"
    OpenJDK Runtime Environment (build 1.6.0-b09)
    OpenJDK Server VM (build 1.6.0-b09, mixed mode)
    -- Program Code ----
    Where <path> = Path i put myself
    package test;
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileReader;
    import java.io.*;
    public class GetInode{
         * @param args
         public static void main(String[] args) {
              GetInode test = new GetInode();
              test.getInode();
         public void getInode(){                    
              String command = "/usr/bin/stat -Lt <path>;
              System.out.println(command);
              Process process;
              Runtime rt;     
              try{
              rt = Runtime.getRuntime();               
              process = rt.exec(command);
              InputStreamReader isr = new InputStreamReader(process.getErrorStream());
              BufferedReader bre = new BufferedReader(isr);
              BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream());
              System.out.println(bre.readLine());
    System.out.println(br.readLine().split(" ")[7]);
              process.destroy();          
              }catch (Exception ex){
                   System.out.println("Error :- " + ex.getMessage());
    ------Output -------------
    /usr/bin/stat -Lt "<path>"
    /usr/bin/stat: cannot stat `"<path>"': No such file or directory
    Error :- null
    Can any one help me what is wrong and why i am unable to run the Linux command from Java.

    For clarity purpose............i m submitting actual code here
    --- Code ---
    package test;
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileReader;
    import java.io.*;
    public class GetInode{
    * @param args
    public static void main(String[] args) {
    GetInode test = new GetInode();
    test.getInode();
    public void getInode(){               
    String command = "/usr/bin/stat -Lt \"/afs/inf.ed.ac.uk/user/s08/s0898671/workspace/CASWESBLIN/TestFS/01_FIL_01.txt.txt\"";
    System.out.println(command);
    Process process;
    Runtime rt;
    try{
    rt = Runtime.getRuntime();
    process = rt.exec(command);
    InputStreamReader isr = new InputStreamReader(process.getErrorStream());
    BufferedReader bre = new BufferedReader(isr);
    BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
    System.out.println(bre.readLine());
    System.out.println(br.readLine().split(" ")[7]);
    process.destroy();
    }catch (Exception ex){
    System.out.println("Error :- " + ex.getMessage());
    --- Output ---
    [ratz]s0898671: java GetInode
    /usr/bin/stat -Lt "/afs/inf.ed.ac.uk/user/s08/s0898671/workspace/CASWESBLIN/TestFS/01_FIL_01.txt.txt"
    /usr/bin/stat: cannot stat `"/afs/inf.ed.ac.uk/user/s08/s0898671/workspace/CASWESBLIN/TestFS/01_FIL_01.txt.txt"': No such file or directory
    Error :- null
    -- Linux Terminal --
    If i copy the first line from the output and execute on Linux terminal her is the output that i get
    [ratz]s0898671: /usr/bin/stat -Lt "/afs/inf.ed.ac.uk/user/s08/s0898671/workspace/CASWESBLIN/TestFS/01_FIL_01.txt.txt"
    /afs/inf.ed.ac.uk/user/s08/s0898671/workspace/CASWESBLIN/TestFS/01_FIL_01.txt.txt 12003 24 81a4 453166 10000 1c 360466554 2 0 1 1246638450 1246638450 1246638450 4096
    Can you just assist me where am i really making mistake.......i was wondering if the command that i pass from Java....can be executed on Linux terminal why is it faling to run from java.........and when i print the Error Stream for process output........it show cannot Stat.......

  • How to execute MySqlDump Command from java..........

    hi friends,Iam used mysqldump command in linux platform to take backup of the database,its work properly....the command am used is
    mysqldump -u root -p threadpool > sampledatabase.sql
    I need to execute the same command in java....?Anyone here to know how to do that....?Thanks in advance........

    Crosspost:
    http://forum.java.sun.com/thread.jspa?threadID=5185230&messageID=9721722#9721722
    http://forum.java.sun.com/thread.jspa?threadID=5185199&messageID=9721587#9721587
    Do not mess the forum.

  • Problem in executing Linux command from Java Programme.

    hi everybody,
    can anybody help me to solve one problem i have.
    i want to capture the output of linux command "grep" in my java programme.but it is not working properly .(maybe this sub-process doesn't have permission to read files)
    here is my code and corresponding outputs.
    import java.io.*;
    public class BSearch
    public static void main(String kj[])
    try
    Runtime rt=Runtime.getRuntime();
    String command="grep \"hello\" -r /usr/MyDir ";               
    Process rtProc=rt.exec(command);          
    InputStream is=rtProc.getInputStream();
    BufferedReader br =new BufferedReader(new InputStreamReader(is));     
    String line =null;
    while((line=br.readLine()) != null)
    System.out.println(br.readLine());
    br.close();
    catch(Exception e)
    System.err.println("Error in command "+e);               
    it finds "hello" pattern only in BSearch.class file although if i fire this command on LINUX prompt it
    shows all the files in /usr/MyDir which contain "hello" pattern.
    java programme output :
    Binary file /usr/MyDir/BSearch.class matches.
    linux command output :
    /usr/MyDir/one.txt: hello sdfs
    Binary file /usr/MyDir/BSearch.class matches.
    /usr/MyDir/two.txt: kjsdf hello sdfsdf
    will anybody help me solve this problem.

    It may be a Problem of Catching the Echoes back from the Processes...I have a Program which Captures the Echoes..see if it works
    import java.beans.PropertyChangeEvent;import java.beans.PropertyChangeListener;import java.beans.PropertyChangeSupport;import java.lang.ref.WeakReference;/** * Implements a proxy property change listener using a weak reference to avoid memory locking that would occur if it * was a strong reference. To understand this, we hve to understand that the property change listeners themselves are * hilding onto panels and other objects with strong java references. If the panel goes away while we are viewing an * object, we have a circular emory hold situation where the panel cant be collected because it has ahold of the * property and the property cannot because it has ahold of the pane. If we use weak references instead, then the hard * link between the listener and the producer is softened to almost nothing. */public class WeakPropertyChangeListener implements PropertyChangeListener {  /**   * A poperty change support object is included here so that the listener can remove   * himself from the listeners if the reference internally goes to null.   */  private PropertyChangeSupport pcs = null;  /** Holds the weak reference to the real listener. */  private WeakReference weakRef = null;  /**   * Constructs a new Proxy object for the given support and listener.   * @param pcs The property change support that this object will be using.   * @param pcl The real listener.   */  public WeakPropertyChangeListener(PropertyChangeSupport pcs, PropertyChangeListener pcl) {    if (pcs == null) throw new NullPointerException("pcs");    if (pcl == null) throw new NullPointerException("pcl");    this.pcs = pcs;    weakRef = new WeakReference(pcl);  } /** @see <{PropertyChangeListener}> */ public void propertyChange(PropertyChangeEvent changeEvent) {    Object referrant = weakRef.get();    if (referrant == null) {      pcs.removePropertyChangeListener(this);    } else {      ((PropertyChangeListener)referrant).propertyChange(changeEvent);    } } /** Returns true for comparison to referrant or this. */ public boolean equals(Object obj) {    if (obj instanceof WeakPropertyChangeListener) return super.equals(obj);    else if (obj != null)return obj.equals(weakRef.get());    else return false;  }}// snipet public void addPropertyChangeListener(PropertyChangeListener listener) {    this.propertyChangeSupport.addPropertyChangeListener(      new WeakPropertyChangeListener(this.propertyChangeSupport, listener));  } public void removePropertyChangeListener(PropertyChangeListener listener) {    this.propertyChangeSupport.removePropertyChangeListener(listener);  }

  • How to execute system command from java program

    Hi all,
    I want to change directory path and then execute bash and other unix commands from a java program. When I execute them separately, it's working. Even in different try-catch block it's working but when I try to incorporate both of them in same try-catch block, I am not able to execute the commands. The change directory command works but it won't show me the effects of the bash and other commands.
    Suggestions??

    The code I am using is....
    try
    String str="cd D:\\Test";
    Process p=Runtime.getRuntime().exec("cmd /c cd
    "+str);your str string is already having cd in it but again you ar giving cd as part of this command also please check this,i will suggest you to remove cd from str
    Process p1=Runtime.getRuntime().exec("cmd /c mkdir
    "+str+"\\test_folder");you should say mkdir once you change your path,but here you are saying mkdir first and then cd D:\Test(this is because of str)..please check this
    Process p2=Runtime.getRuntime().exec("cmd /c bash");
    Process p3=Runtime.getRuntime().exec("cmd /c echo
    himanshu>name.txt");
    catch(IOException e)
    System.err.println("Error on exec() method");
    e.printStackTrace();
    Message was edited by:
    ragas

  • Executing linux command from Java code

    Hi ,
    I have a web application running on JBoss on Linux platform.
    I need to execut certain shell command of linux through servlet or JSP, so that I can display the command results on UI.
    If you have done something similer sort of thing then please shed some light on it.
    TIA,
    Sachin

    Sorry for the wrong post...please ignore this..
    Thanks,

  • Execute shell command from Java

    Hi all,
    I need some idea for executing shell script from Java programe.
    For example i have start.sh script in /tmp/start.sh  folder of unix server.
    I want to execute shell script from local java code.
    Any idea on this.

    Hi,
           Read the following articles/posts, maybe this could help you:
          How to execute shell command from Java
    Running system commands in Java applications | java exec example | alvinalexander.com
    Want to invoke a linux shell command from Java - Stack Overflow

  • How to call gnuplot command from java

    Hi there,
    In our course, we are required to develop an GUI for gnuplot. In case you don't know about gnuplot, it's a plotting program and has lots of command. We want to use java and swing, but now we don't know how to call gnuplot command from java, or how to execute a shell command(script) from java.
    By the way, since we need read in files with several columns of data and allow user to select a column, we want to use JTable. Is that reasonable?
    Thanks a lot for any suggestions!
    Jack

    Hi, there:
    Will using JTable add much overhead? I may have to use several JTables and switch among them. I can add scroll bar to or edit JTables, right?
    BTW, do you have experience about gnuplot? Can I find the command tree of gnuplot somewhere? Or do you know a better place to post question about gnuplot? unix/linux group, maybe.
    Thanks,
    Jack
    P.S. Would you guys answer my question after I use up my duke dollars? :- )

  • Execute operatingsystem commands from java classes?

    How can I execute operatingsystem commands from my java classes?
    So that I on a Linux box could i.e. execute "ls -l" etc.

    Also read this:
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html

  • Executing shell commands from Java.

    I want to execute shell commands in Java using the Runtime.exec( String ) method.
    The method works fine under Linux OS, but under Windows '98 the method didn't work at all!
    For example the following call: Runtime.exec( "dir" ) throws an exception showing that the command was not completed. If I replace dir with ls under Linux all is good. What is the problem with the Microsoft Windows '98 ? Is there any solution at my problem ?!
    thx in advance!

    hey JSarmis,
    You can help me... "ls" doesn't work for me on linux.. using Runtime.exec, some commands work, others don't... you may hold the key to what i need? How did u get "ls" to work?

  • Execute unix commands from Java

    Hi,
    I have a client application running on windows. This client should connect to a unix server and check for the existence of a file and display the result as "File found/File not found". In order to connect from windows to the unix server, I used the sockets and the connection is successfully established. The second part is to check for the presence of the file in unix server. I searched in google.com and the option I found to execute a unix command from java is the "Runtime.exec()". Runtime.exec is considered as the less effective (not a favorable) one.
    Is there any other option available (other than the Runtime) to execute the unix command from java? Can you please let me know.
    Thanks a lot
    Aishu

    So, please let me know how I can execute the above unix commands without Runtime.exec()You have a client and a server.
    You want something to run on the server, not the client.
    That means that something must in fact being running on the server before the client does anything at all.
    For example telnet. Or a J2EE server application.
    So is something like that running?
    If not then there absolutely no way to do what you want, even with Runtime.exec().
    If yes then what you do depends on what is running. So Runtime.exec() would be pointless if a J2EE server was running.

  • How to execute unix command from ODI Procedure

    Hi,
    I am trying to execute below unix command from ODI Procedure (Command on Target tab) but I am getting the error "java.io.IOException: Cannot run program "cd": error=2, No such file or directory" but when I try to execute the same command using OdiOSCommand, it is executing successfully. I don't want to use shell script to execute this command. Is there any specific syntax am I missing to execute this command from ODI procedure?
    cd /project3/tmt/;ls *.dmp > dmplist.lst
    Please help me on this...
    Thanks
    MT

    Hi nahlikh,
    Thank you for the reply.
    I used below command in Procedure but still getting the same error as "java.io.IOException: Cannot run program "OdiOSCommand": error=2, No such file or directory".
    OdiOSCommand "-COMMAND=cd /project3/tmt/;ls *.dmp > dmplist.lst"
    as I mentioned earlier if I use the command cd /project3/tmt/;ls *.dmp > dmplist.lst in OdiOSCommand tool it is executing successfully without any issues.
    any thoughts appreciated to get a solution for this issue.
    Thanks
    MT

  • How to run system commands from JAVA

    Hi Friends,
    How to run windows system commands from JAVA
    Runtime r=Runtime.getRuntime();
    r.exec("dir");
    Throwing following Exception
    CreateProcess :dir error=2
    Thanks in advance
    Hamsa

    Hi ,
    in Windows NT this is not possible, you can use the following :
    Runtime r=Runtime.getRuntime();
    StringBuffer sbuf = new StringBuffer();
    String dir = new String();
    java.lang.Process proc = r.exec("cmd /c dir");
    InputStream is = proc.getInputStream();
    int ch ;
    while((ch=is.read() ) != -1)
    sbuf.append((char)ch);
    is.close();
    dir = sbuf.toString();
    System.out.println(dir );

  • How to execute dos command in Java program?

    In Perl, it has System(command) to call dos command.
    Does java have this thing?
    or any other way to execute dos command in java program?
    Because i must call javacto compile a file when the user inputed a java file name.

    Look in the Runtime class, it is implemented using the Singleton design pattern so you have to use the static method getRuntime to get its only instance, on that instance you can invoke methods like
    exec(String command) that will execute that command in a dos shell.
    Regards,
    Gerrit.

Maybe you are looking for

  • What is causing my Safari to crash at least once a day?

    I can't figure it out! I tried the whole plug-in thing where you test and see, but that didn't work. What does my report say? Process: Safari [22619] Path: /Applications/Safari.app/Contents/MacOS/Safari Identifier: com.apple.Safari Version: 5.0.3 (65

  • Which wire on the 30-pin plug is responsible for charging an Ipod?

    Which wire on the 30-pin plug is responsible for charging an Ipod? I want to cut this wire so that I can use my Ipod in my car or on my computer without having to charge it. I understand that Ipod's are meant to withstand short charges, but I still w

  • IPod nano -- unknown USB device

    Hi. My iPod worked perfectly for 2 weeks. Since this morning, when I connect it to my PC a message "Unoknown USB Device" is showed. I know how to reset mi iPod, but it doesn't work. I have 6 USB ports 2.0, I used all of them and that doesn't work. I

  • Losing wifi when connecting my cintiq 21UX to my 2014 iMac

    Last week I bought a new iMac and when I connect (via Thunderbolt & USB) my Cintiq 21UX  to it I lose my wifi connection - obviously I'd like to have both working at the same time - any ideas?? Marc

  • Connect to InterBase

    Hello. I wonder if smbd can hint with examples how to work with InterBase databases in java: connect, prossed SQL queries so on...? Thanks