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?

Similar Messages

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

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

  • Execute shell command from within pascal code

    Hello there,
    I am trying to execute a shell command from within my pascal code. I use XCode together with FreePascal. I have tried something like:
    exec ('program', 'options');
    adding the 'Dos' unit to the Uses clause of my program.
    Thus, e.g.,
    exec ('mkdir', '/A')
    to create a directory with the name 'A'.
    However, my attempts so far were unsuccessful. Can anyone help me on this, and perhaps provide a simple example of how to do it right?
    Thank you in advance,
    Shane

    In the mean time, I found the problem myself. I am just posting the solution here for anyone that is interested. My original solution was correct, in that the 'Dos' Unit must be added, and that the right command is 'exec'. There was however a problem with the correct path to the program that I wanted to invoke. In the shell, this program was accessible from anywhere. However, in the 'exec' command, the full path to the program must be given. Since I am not a Unix expert, I don't know the reason for this.
    So, in summary, the solution is:
    Uses Dos;
    begin
    exec ('full path to program', 'program options');
    e.g.: exec ('/bin/sh', '/run.sh') to process the commands in the file /run.sh
    end
    Hope this may be of help to anyone else.
    Shane
    Mac OS X (10.3.9)
    Mac OS X (10.3.9)
    Mac OS X (10.3.9)

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

  • 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

  • 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

  • Execute DOS command from java application

    Hello,
    I want to execute a DOS command (MOVE, in order to move an image from a folder to an other) from a java application. How can I do this?
    Francesco

    Yes I have tested it and it is working but only when executing a bacth file. For instance:
    Runtime rt = Runtime.getRuntime();
    try{
         Process proc = rt.exec("move.bat");
    }catch(Exception ex){
         ex.printStackTrace();
    }and the command in move.bat is:
    move c:\\temp\\*.gif C:\\temp2
    You don't have to use double slashes in batch files, only in Java. But anyway it is working both ways.
    It is not working when you try to execute the command without the batch file:
    Process proc = rt.exec("move c:\\temp\\*.gif C:\\temp2"); -> this will not work.
    It should work. Try to execute another command to see what happens.

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

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

  • Starting an executable system command from java

    I'm new to Java and i was wondering : is it possible to start an executable from Java under Windows? If so, how?
    Thanx

    There are only about 9 billion responses a day on how to do this. Use the search feature.

  • Executing shell commands in Java

    Hi
    I have managed to get my Java program to execute the 'who' command and read in the data from running that command. However, how can I run this command with the '-m' option. I thought it would be
    Process proc = rt.exec("who -m");However when I run this, I get no data. Is there another way of running this command.
    Many thanks
    Sambo

    Thanks for the link, its actually the tutorial I looked at to start using the exec method.
    try{
                   Runtime rt = Runtime.getRuntime();
                   Process proc = rt.exec("who");
                   InputStream stderr = proc.getInputStream();
                   InputStreamReader isr = new InputStreamReader(stderr);
                   BufferedReader br = new BufferedReader(isr);
                   File file = new File("input.txt");
                   BufferedWriter out = new BufferedWriter(new FileWriter(file));
                   while ((line = br.readLine())!=null){
                        temp = line.split("\\s+");
                        for (int i = 0; i < temp.length; i++){
                            //System.out.println(temp);
    This is my current code, and I can get an output from that. But as soon as I add a argument to the who command, it doesn't display anything. The who command displays the current users logged into a Linux system.
    I have tried
    Process proc = rt.exec("who -m");and
    Process proc = rt.exec("who ", "-m");But no luck.
    Maybe I have to specify it as another argument, but not to sure how to do that.
    Again many thanks

  • Execute Unix command from Java program running on windows

    Hello,
    I need to write a java program that fetches file count in a particular unix machine directory. But java program will be running on windows machine.
    The program should execute unix list command and fetch the output of that command.
    Can anyone help me on this?
    Thanks.

    Hi there,
    I had a similiar problem, though years ago. It was to have a java program execute any other. Lately, I've had to have a java program running on a unix machine execute a shell script. Entirely two different scenarios. I'm not sure what you will need for your app, but look into this:
    Java Native Interface for executing C/C++ code.
    C/C++ Code for launching the program you need to run.
    java.lang.Runtime(?).exec(....)
    With a combination of that stuff, you can make a launcher for any os that has Java running on it, and with Runtime, you can exec() pretty near any sort of unix shell or app command you'd like.
    Good luck.
    Tim

Maybe you are looking for

  • What is the best way to set up itunes with 2 different ipods on same desktop?

    I have a new computer, was able to transfer itunes fine.  now having probs figuring out how to set up 2 ipods.  older ones - 2gb nano and a 30gb classic.  wld like to use same library.  thought about setting up 3 itunes - one main, one for each ipod.

  • HT1430 How do you power off a i Phone in Assistive Touch?

    I have to use Assistive Touch on my phone because the power button does not work, how do I power off the phone completely when I use Assistive Touch?

  • Can we write Spel Language Programatically

    Hi All Is it possible to write Spel Language Programatically ? For example , Can I have a code that reads as follows ? Line 1 : OAMessageTextInputBean descBean = (OAMessageTextInputBean)webBean.findChildRecursive("Description"); Line 2: descBean.setR

  • Login Issues related to JavaServer Faces

    I'm trying to login to my application on the server and I get the following error. Any guidance or suggestions on how to fix this problem? I have the jsf's located in the WEB-INF/lib directory. javax.faces.FacesException: Assertion Failed      at com

  • Production Order Journal Posting - contain duplicate GL Accounts

    Hi All, We have encountered a rather strange occurance at one of our customer who is in the manufacturing sector.  When a journal is created from the Production 'Receipt from Production' the Journal contents is as follows: 130000 Raw Material DR £100