How to execute a Unix Command in java

Hi, Iam trying to execute a unix command on Sun Solaris by passing that command to a java program. How can I achieve this?
Thanks in advance.

Have a look at the javadoc around the Runtime.exec() method. If the command is a shell command then you might have to execute a shell as well as the command.
For example, if you wanted to run a unix command 'ls -l > output.txt' the you might have to pass the following string into the exec() method,
"/bin/sh ls -l > output.txt'

Similar Messages

  • How to execute a shell command in java?

    here, my environment is redhat 7, jdk 1.5.
    i don't know how to use the shell command in java.
    i want to use this function:
    #include <stdlib.h>
    int system(const char * string);
    please give me some ideas. and Thank you so much if coming with a little demo.

    i know i should use JNI. because i have to use C lib.
    but i have already use JNI to wrapper the original code the cpp code and java code is :
    //: appendixb:UseObjImpl.cpp
    //# Tested with VC++ & BC++. Include path must
    //# be adjusted to find the JNI headers. See
    //# the makefile for this chapter (in the
    //# downloadable source code) for an example.
    #include <jni.h>
    #include <stdlib.h>
    extern "C" JNIEXPORT void JNICALL
    Java_UseObjects_changeObject(
    JNIEnv* env, jobject, jobject obj) {
    jclass cls = env->GetObjectClass(obj);
    jfieldID fid = env->GetFieldID(
    cls, "aValue", "I");
    jmethodID mid = env->GetMethodID(
    cls, "divByTwo", "()V");
    int value = env->GetIntField(obj, fid);
    printf("Native: %d\n", value);
    env->SetIntField(obj, fid, 6);
    env->CallVoidMethod(obj, mid);
    value = env->GetIntField(obj, fid);
    system("preprocess -path sha.c");
    printf("Native: %d\n", value);
    } ///:~
    //: appendixb:UseObjects.java
    // From 'Thinking in Java, 2nd ed.' by Bruce Eckel
    // www.BruceEckel.com. See copyright notice in CopyRight.txt.
    class MyJavaClass {
    public int aValue;
    public void divByTwo() { aValue /= 2; }
    public class UseObjects {
    private native void
    changeObject(MyJavaClass obj);
    static {
    // System.loadLibrary("UseObjImpl");
    // Linux hack, if you can't get your library
    // path set in your environment:
    System.load(
    "/root/jproj/UseObjImpl.so");
    public static void main(String[] args) {
    UseObjects app = new UseObjects();
    MyJavaClass anObj = new MyJavaClass();
    anObj.aValue = 2;
    app.changeObject(anObj);
    System.out.println("Java: " + anObj.aValue);
    } ///:~
    i modify this two file which is from TIJ-2edition.
    the output is
    Native: 2
    Native: 3
    Java: 3
    but what i want to be executed "preprocess -path sha.c" does not work.
    i have change the command to, such as "df", "ls" etc. but none of them works
    please help me.

  • Problem in executing a unix command through java

    hi
    i'm trying to execute unix command through java
    simple shell command like "ls -l >test " but i'm not able to see the result.
    there are no error messages.
    Code is:
    import java.lang.Runtime.*;
    class ExecDemo
         public static void main(String[] args)
              Runtime r=Runtime.getRuntime();
              Process p=null;
              try
                   p=r.exec("ls -l > test");
              catch (Exception e)
                   System.out.println("Error executing nedit.");
    }can anyone help please.

    get the the inputStream of the runtime object after executing the command.
    now use the readLine() function until it becomes null.
    egs: with reference to ur code.
    InputStream is=p.getInputStream()
    while(is!=null)
    String s=is.readLine();
    if the command don't execute try giving the full path also like /sbin/ls -l

  • How to execute any cmd command from java application?

    Hi all,
    How to execute or call any command of cmd from java application??
    Is there any method to do so??
    Or, is it possible to do it using Runtime.exec() ??? And if so, how to use it, please explain with ab example...
    I'll highly appreciate....
    Thank you.

    If google would be the best option, then I would not be on Sun's forums and I would not have asked experts like you, sir !! :-)
    Neway, I got the solution from PhHein !!
    Good link indeed..
    Cheers..

  • How to run a unix command in java

    Hi all,
    I need to run a unix command in my standalone java application.my java program is in windows.Is it possible to run unix command on windows system.help me out.
    I tried this
    Process p = Runtime.getRuntime().exec("ps -ef");
                BufferedReader stdInput = new BufferedReader(new
                     InputStreamReader(p.getInputStream()));
                BufferedReader stdError = new BufferedReader(new
                     InputStreamReader(p.getErrorStream()));i get IO Exception -Create Process ps-ef error=2

    If you want to run a command from java for a windows platform, you should check windows knows the command.
    So, load up a DOS prompt and type ps -ef and see what happens.

  • How to execute the ldapsearch command by java class in linux os?

    hi,all
    I want to query the users by ldapsearch command. I call the command in my java class. In windows, It work well. But in linux , there haven't any result. My test program is following:
    ===============
    import java.util.*;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.LineNumberReader;
    public class test{
    public static Vector queryAllUser(){
    try{
    Vector v=new Vector();
    String cmdquery="ldapsearch -h localhost -b\"dc=metasphere,dc=com\" \"uid=*\" uid ";
    //String cmdquery="ls -la";
    Process process=Runtime.getRuntime().exec(cmdquery);
    System.out.println("cmdquery:"+cmdquery);
    InputStreamReader ir=new InputStreamReader(process.getInputStream());
    LineNumberReader input = new LineNumberReader (ir);
    System.out.println("input="+input);
    String line;
    while ((line = input.readLine ()) != null){
    System.out.println("Line:"+line);
    if(line.startsWith("uid")){
    String temp=line.substring(line.indexOf(":")+1,line.length());
    v.add(temp);
    return v;
    }catch(Exception e){
    e.printStackTrace();
    System.out.println("runtime error:"+e.getMessage());
    return null;
    public static void main(String argv[]){
    Vector v=queryAllUser();
    for(int i=0;i<v.size();i++){
    System.out.println((String)v.get(i));
    ================
    In fact, when I execute the command: ldapsearch -h localhost -b"dc=metasphere,dc=com" "uid=*" uid
    in linux prompt, the screen show the results:
    version: 1
    dn: uid=toppymgt,dc=metasphere,dc=com
    uid: toppymgt
    dn: uid=qutao,dc=metasphere,dc=com
    uid: qutao
    dn: uid=zz,dc=metasphere,dc=com
    uid: zz
    dn: uid=z,dc=metasphere,dc=com
    uid: z
    dn: uid=admin,dc=metasphere,dc=com
    uid: admin
    dn: uid=alan,dc=metasphere,dc=com
    uid: alan
    dn: uid=misssixty,dc=metasphere,dc=com
    uid: misssixty
    dn: uid=channelv,dc=metasphere,dc=com
    uid: channelv
    What's reason? Please help me. Thx.

    If there have a bugs in Linux OS. Please help me!

  • How to execute MS DOS command through Java program???

    Dear Sir,
    I want to run a MS-DOS command through my Java program. I have tried "Dir" command but no other command which takes command line args doesn't work at all. Please help.
    import java.io.*;
    class CommandPrompt
         public static void main(String[] args)
              try
                   File file = new File("C:/Temp/Java");
                   String[] cmd = {"command.com","/c","md folder"};
                   String[] envp = {""};
                   Process m;
                   String s = "";
                   m = Runtime.getRuntime().exec(cmd,null,file);
                   BufferedReader buf = new BufferedReader(new InputStreamReader(m.getInputStream()));
                   while ((s = buf.readLine())!=null)
                        System.out.println(s);
              catch (Exception ex)
                   System.out.println("Exception is "+ex);
                   ex.printStackTrace();

    1. This forum is for Swing-related issues only. This question should be posted to the "Java Programming" forum.
    2. Please enclose your sample code in code blocks; it's much easier to read that way. See here for how it's done: http://forum.java.sun.com/faq.jsp#messageformat
    3. Please provide more information, like what error messages you got and what OS you're running. For instance, if you're running WinXP, Win2k or NT4, your command processor should be "cmd.exe", not "command.com". When I made that change, your program worked for me.

  • How to execute unix command in java  or jsp

    have a peace day,
    please send some sample code for
    "execute the unix command in java or jsp"
    thank you
    regards
    rex

    i execute this coding
    its compiling. while running i get the error " java.io.IOException: CreateProcess: \ls-l error=2 "
    import java.io.*;
    import java.util.*;
    public class Test
       public static void main(String[] args) throws Exception
         try
              String[] cmd = {"/ls-l"};
    Runtime.getRuntime().exec(cmd);
         catch (Exception e)
               System.out.println(e);
      }what can i do for that
    thank u

  • Execute unix command using java

    Hello
    Can we execute a unix command using java? If it is how we can execute. Is this affect the performance of the program.
    Thanks

    I tried what you said. But its not working and returning error message,
    java.io.IOException: CreateProcess: ls -a error=2
         at java.lang.ProcessImpl.create(Native Method)
         at java.lang.ProcessImpl.<init>(Unknown Source)
         at java.lang.ProcessImpl.start(Unknown Source)
         at java.lang.ProcessBuilder.start(Unknown Source)
         at java.lang.Runtime.exec(Unknown Source)
         at java.lang.Runtime.exec(Unknown Source)
         at java.lang.Runtime.exec(Unknown Source)
    If i try this statement,
    Runtime.getRuntime().exec("c\windows\notepad");
    It is working fine.
    Any idea about this.
    Plz ...........

  • 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 a unix/dos command in Java

    Hi,
    I want to execute dos/unix commands in my java program. Can anyone tell me how to do this. Say I want to restart my httpd daemon using the command: "service httpd restart" or test my httpd.conf file using the command "testparn"
    thanks in advance
    Hugo Hendriks

    hallo,
    test this:
    Process p = Runtime.getRuntime().exec(Your_Programm);
    p.waitFor();
    LineNumberReader lnr = new LineNumberReader(new InputStreamReader(p.getInputStream()));
    Your_Programm must be a shellscript. regard that your java programm must have the right to start the httpd!
    Carsten Bluetner

  • Through a java prog how to execute a unix script ?

    Hi !! I am a Java Developer . I have to work in Unix and Java in combination. Can you plz suggest me a solution for the below queries --
    1. Through a java prog how to execute a unix script.
    2. How to send the o/p of the script to a java prog so that it can be used in the java program to the prupose of display etc..

    Try this
    Process process = Runtime.getRuntime().exec("ps -ef");//write Your command here
                   InputStream in = process.getInputStream();
                   BufferedReader bufReader = new BufferedReader(new InputStreamReader(in));
                   String data=null;
                   while((data = bufReader.readLine())!=null)
                        System.out.println(data);   //do whatever you want to do with the output

  • Permission denied when I execute a unix command from within my java applet.

    Hi Gang,
    Forgive me if this is not the appropriate forum for this problem. I'm posting this problem on this forum since I got no answers on the other forum I posted on.
    I've written a simple java applet that runs a unix command and then displays some information. The applet compiles fine, and runs perfectly from the command line on my unix system.
    However, when I point a browser at the applet from my desktop PC I get the following error as taken from the java console:
    Exception in thread "AWT-EventQueue-2" java.security.AccessControlException: access denied (java.io.FilePermission <<ALL FILES>> execute)
    This is of course the first line in a long line of error messages. It appears that I am not able to execute a command on the unix system through my applet. I know the problem is with trying to execute a unix command since commenting it causes no error in the web browser. This is the command I'm using in java to execute the unix command:
    p = Runtime.getRuntime().exec("ps");
    Here's the html file on the unix system:
    <html>
    <head></head>
    <body>
    <appletcode=G.class height="250" width="400">
    Your browser does not support the applet tag.
    </applet>
    </body>
    </html>
    I won't list the java code since it is compiling and working on the command line. But, if you want to see it I'll provide it.
    I've done quite a bit of research on this and it seems that a great number of people have similar problems reading or executing files through java. I have yet to find a solution to this problem.
    Here are some details about my setup:
    Server:
    HP9000 running HP/UX 11.23
    Apache Web Server 2.0.35
    Java 1.5
    Desktop PC:
    Win2K Pro
    Internet Explorer 6
    Java 1.6
    If you have a solution I would be very grateful! This problem is keeping me from writing my application!
    thanks!
    kev

    Multi-posted.
    Already answered here http://forum.java.sun.com/thread.jspa?threadID=5225314&messageID=9916327#9916327

  • Permission denied when I execute a unix command from inside my Java applet.

    Hi Gang,
    Forgive me if I'm posting this to the wrong forum! I didn't get any answers on the previous forum that I posted this to.
    I've written a simple java applet that runs a unix command and then displays some information. The applet compiles fine, and runs perfectly from the command line on my unix system.
    However, when I point a browser at the applet from my desktop PC I get the following error as taken from the java console:
    Exception in thread "AWT-EventQueue-2" java.security.AccessControlException: access denied (java.io.FilePermission <<ALL FILES>> execute)
    This is of course the first line in a long line of error messages. It appears that I am not able to execute a command on the unix system through my applet. I know the problem is with trying to execute a unix command since commenting it causes no error in the web browser. This is the command I'm using in java to execute the unix command:
    p = Runtime.getRuntime().exec("ps");
    Here's the html file on the unix system:
    <html>
    <head></head>
    <body>
    <appletcode=G.class height="250" width="400">
    Your browser does not support the applet tag.
    </applet>
    </body>
    </html>
    I won't list the java code since it is compiling and working on the command line. But, if you want to see it I'll provide it.
    I've done quite a bit of research on this and it seems that a great number of people have similar problems reading or executing files through java. I have yet to find a solution to this problem.
    Here are some details about my setup:
    Server:
    HP9000 running HP/UX 11.23
    Apache Web Server 2.0.35
    Java 1.5
    Desktop PC:
    Win2K Pro
    Internet Explorer 6
    Java 1.6
    If you have a solution I would be very grateful! This problem is keeping me from writing my application!
    thanks!
    kev

    Multi-posted.
    Already answered here http://forum.java.sun.com/thread.jspa?threadID=5225314&messageID=9916327#9916327

  • Execute an Unix command with pipe

    Hi,
    How do I execute a unix command with pipe from JAVA runTime.exec(cmd)? for example: "ls -l |wc -l"
    should return number of files. However, there is no output result. If I use "ls -l" as command argument, it gives file list.
    Here is my program:
    public static void main(String[] args) {
    try {
    Runtime runCmd = Runtime.getRuntime();
    System.out.println("sys testing");
    Process retProc = runCmd.exec(args[0]);
    BufferedReader bread = new BufferedReader
    (new InputStreamReader(retProc.getInputStream()) );
    String out = bread.readLine();
    while ( out != null ) {
    System.out.println(out);
    out = bread.readLine();
    DataOutputStream outSt = new DataOutputStream(retProc.getOutputStream() );
    outSt.writeChars(args[1]);
    outSt.flush();
    } catch (Exception ie) {
    ie.printStackTrace();
    Thanks in advance,
    Jeff

    I got my answer !
    No need to reply

Maybe you are looking for

  • Line-in Port Question

    Okay, I understand now that the port I thought was a mic port on my 2008 Macbook Pro is a line-in port. What I don't understand though is why my headset worked fine with it up until last week. Can anyone help me understand why this would be?

  • How to make iTunes forget the CDDB info and reread from Gracenote ?

    I have some CD which have 2 entries in Gracenote. (These are Chinese CDs, and Gracenote has 2 set of info, one in Chinese and another in English). I picked the English one, and it populated the tags, but now I want to use the Chinese information inst

  • Script to close old service requests from date X backwards

    Running 12.1.3 We have a bunch of service requests that are old and need to be closed. Most are from 2005 back. There are around 1600 of them I would like to close but doing it by hand it not really an option. Is there a script I can run to close eve

  • Lost wifi connection during iTunes download

    I frequently got my wifi network dropped when I try to download iOS updates or apps updates through iTune. I would lose all network connection despite the wifi signal is still strong. I need to turn off the wifi on my iMac and then turn it back on to

  • Black screen - Xorg/GDM config - Nvidia Optimus? [solved]

    Hi! I have a Samsung RC539 S09, which has got an Nvidia Optimus graphics card, I want a graphical Xserver on that machine. Therefore I followed the wiki and installed the Nvidia stuff (https://wiki.archlinux.org/index.php/NVIDIA). I did not configure