Executing the top command through Java in linux

I am trying to execute the top command in Java as
Runtime.getRuntime().exec("top -n 1 >a.log");
But the command is not working in linux only through java.When i run the same command through the prompt it is working fine.Also all other commands are working fine.Is there any issue with top in linux?

flounder wrote:
Try reading [this article|http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html]. If it does not answer your problem then try seaching for other similar articles.
The cited article does provide an answer to the problem since it explains how the shell meta character '>' must be interpretted by a shell. The code as presented does not invoke a shell.

Similar Messages

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

  • We are trying to implement a process so that any document that needs to be printed through our Java application will be printed as PDF using Adobe Reader. For which, We created and execute the below command line to call Adobe Reader and print the PDF on a

    We are trying to implement a process so that any document that needs to be printed through our Java application will be printed as PDF using Adobe Reader. For which, We created and execute the below command line to call Adobe Reader and print the PDF on a printer."C:\Program Files (x86)\Adobe\Reader 11.0\Reader\AcroRd32.exe" /T "\\<Application Server>\Report\<TEST.PDF>" "<Printer Name>". Current Situation: The above command line parameter when executed is working as expected in a User's Workspace. When executed in a command line on the Application Server is working as expected. But, the same is not working while executing it from Deployed environment.Software being used: 1. Adobe 11.0 enterprise version. 2. Webshpere Application Server 8.5.5.2. Please let us know if there is a way to enable trace logs in Adobe Reader to further diagnose this issue.

    This is the Acrobat.com forum.  Your question will have a much better chance being addressed in the Acrobat SDK forum.

  • Execute dos commands through java

    Hi,
    Im trying to execute dos commands through java like
              try {
                   java.lang.Runtime.getRuntime().exec("cmd /c cls");
              }catch(IOException e){
                   System.out.println(e.getMessage());
              }Not sure if its possible? however
    open notepad would work
              try {
                   java.lang.Runtime.getRuntime().exec("notepad");
              }catch(IOException e){
                   System.out.println(e.getMessage());
              }Im trying to execute a cls commands to clear screen but without luck.

    The question is, which shell do you want to clear?
    I don't really know, but it could be that Runtime.exec executes its command in a new shell window...

  • What is the best way to call SSH commands through Java technologies

    What is the best way to call SSH commands through Java technologies

    I don't think you can specify the password at the prompt using ssh. Plink has the -pw command option for passwords. What I did was except ssh to ask me and write the password programmatically through the outputStream I obtained from my Process object. I looked for "password: ", and then wrote the password with a trailing newline.
    Both plink and ssh will also ask if you trust the host if it is the first time you are connecting to it. So before just writing the password, check if the program wants verification from you: normally supplying "y" or "n". This should only have to happen the first time the client connects. It looks like thisPLINK:
    The server's host key is not cached in the registry. You
    have no guarantee that the server is the computer you
    think it is.
    The server's key fingerprint is:
    1024 f8:43:61:4c:a2:5b:77:be:5b:a7:bb:1f:f7:79:b3:b7
    If you trust this host, enter "y" to add the key to
    PuTTY's cache and carry on connecting.
    If you want to carry on connecting just once, without
    adding the key to the cache, enter "n".
    If you do not trust this host, press Return to abandon the
    connection.
    Store key in cache? (y/n)
    SSH:
    The authenticity of host '127.0.0.1 (127.0.0.1)' can't be established.
    RSA key fingerprint is e1:02:13:c8:52:c2:23:41:9b:5b:58:2c:18:e6:59:af.
    Are you sure you want to continue connecting (yes/no)?What I did was read character by character from the inputStream until I found things of interest ... like "password: ". You only need to search for this in your method which will launch the ssh or plink Process. Once you have verifyed yourself, you can just pass commands to the Process, which is an ssh connection.
    My suggestion is to read() each byte from the Process's inputStream and write it to stdout. Look and see what you need to be looking for so you can interactive with the program correctly. You can't use readLine here becuase when the ssh asks for the password it does not print a newline. I do know for sure, that ssh will simply print, "passowrd: ". Plink will print this as well if the -pw option is not supplied.

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

  • Host command through java stored procedure

    Hi All,
    Im trying to execute the winword command to open a MSWord document, print & exit the document, through dos prompt, from client pc to the default printer, through java stored procedure oracle pl/sql forms.
    How can achieve this? Kindly help.
    rgs
    paul

    If you have configured webutil without any problems then i presume you have configured jacob.jar file too for Client_ole2 to function properly you need to have jacob.jar and jacob.dll files.
    There are so many topics in this forum for Client_Ole2. Just simply search. :)
    Message was edited by:
    Mudabbir

  • PROBLEM in executing a shell command through Runtime.getRuntime().exec()

    Hi all,
    I was trying to execute the following code:
    import java.io.BufferedReader;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.sql.CallableStatement;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.Statement;
    import java.sql.ResultSet;
    * Created on Mar 13, 2007
    * To change the template for this generated file go to
    * Window>Preferences>Java>Code Generation>Code and Comments
    * @author 195092
    * To change the template for this generated type comment go to
    * Window>Preferences>Java>Code Generation>Code and Comments
    public class ClassReportDeleteDaemon {
         ClassReportDeleteDaemon()
         public static void main(String[] args) throws Exception
              Connection conn = null;
              Statement stmt = null;
              ResultSet rs;
              String strQuery = null;
              String strdaysback = null;
              String delstring = null;
              int daysback;
              try
                   System.out.println("REPORT DELETION ::: FINDING DRIVER");               
                   Class.forName("oracle.jdbc.driver.OracleDriver");
              catch(Exception e)
                   System.out.println("REPORT DELETION ::: DRIVER EXCEPTION--" + e.getMessage());
                   System.out.println("REPORT DELETION ::: DRIVER NOT FOUND");
              try
                   String strUrl = "jdbc:Oracle:thin:" + args[0] + "/" + args[1] + "@" + args[2];
                   System.out.println("REPORT DELETION ::: TRYING FOR JDBC CONNECTION");
                   conn = DriverManager.getConnection(strUrl);
                   System.out.println("REPORT DELETION ::: SUCCESSFUL CONNECTION");
                   while(true)
                        System.out.println("WHILE LOOP");
                        stmt = conn.createStatement();
                        strQuery = "SELECT REP_DAYS_OLD FROM T_REPORT_DEL";
                        rs = stmt.executeQuery(strQuery);
                        while(rs.next())
                             strdaysback = rs.getString("REP_DAYS_OLD");
                             //daysback = Integer.parseInt(strdaysback);
                        System.out.print("NO of Days===>" + strdaysback);
                        delstring = "find /tmp/reports1 -name " + "\"" + "*" + "\"" + " -mtime +" + strdaysback + " -print|xargs rm -r";
                        System.out.println("DELETE STRING===>" + delstring);
                        Process proc = Runtime.getRuntime().exec(delstring);
                        //Get error stream to display error messages encountered during execution of command
                        InputStream errStream=proc.getErrorStream();
                        //Get error stream to display output messages encountered during execution of command
                        InputStream inStream = proc.getInputStream();
                        InputStreamReader strReader = new InputStreamReader(errStream);
                        BufferedReader br = new BufferedReader(strReader);
                        String strLine = null;
                        while((strLine=br.readLine())!=null)
                             System.out.println(strLine);
                   }     //end of while loop
              }     //end of try
              catch (Exception e)
                   System.out.println("REPORT DELETION ::: EXCEPTION---" + e.getMessage());
                   conn.close();
         }     //end of main
    }     //end of ClassReportDeleteDaemon
    But it is giving the error "BAD OPTION -print|xargs". The command run well in shell.
    Please help.
    Thanking u.......

    Since the pipe '|' is interpreted by the shell then you need the shell to invoke your command
            String[] command = {"sh","-c","find /tmp/reports1 -name " + "\"" + "*" + "\"" + " -mtime +" + strdaysback + " -print|xargs rm -r"};
            final Process process = Runtime.getRuntime().exec(command);
      You should also read http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html at least twice and implement the recommendation regarding stdout and stderr.
    P.S. Why are you not using Java to find and delete these files?
    Message was edited by:
    sabre150

  • Issue while executing the discovery command from target nodes

    Hi Experts.
    I had to create cluster two node using openfile, after creation of successful lun and associated partition from all the nodes i have changed the ip address of openfiler.
    After changing the IP on open filer.
    A) openfile version:-
    [root@san ~]# uname -r
    2.6.26.8-1.0.11.smp.pae.gcc3.4.x86.i686
    B) Linux Oel5:-
    [root@rac1 ~]# uname -r
    2.6.18-194.el5xen
    [root@rac1 ~]#
    1:- I am able to ping and ssh etc from any node to openfiler.
    However, while executing the below command i am facing the below exception..
    service iscsi restart
    Stopping iSCSI daemon:
    iscsid dead but pid file exists [  OK  ]
    Starting iSCSI daemon: [  OK  ]
    [  OK  ]
    Setting up iSCSI targets: iscsiadm: No records found!
    [  OK  ]
    [root@rac1 ~]#
    Moreover, tried to discover the targets, unfortunately no message is getting displayed after execution of this below command.
    [root@rac1 ~]# iscsiadm -m discovery -t sendtargets -p 192.168.37.200
    [root@rac1 ~]#
    The quick response will be appreciated as my whole test case is down as of now due storage issues.
    Thanks,
    Arch.

    Are you running a firewall that needs to be adjusted to support your changed Openfiler IP network?

  • Calling the system commands in Java

    Hi All,
    How to call the system commands in java other than using
    exec() function.For eg, in my linux machine i have used p.exec("exit") to exit from a cshell to the prompt but it is not working.Is there any other solution for this one. Pls. do provide a solution for this.It is quite Urgent.
    Thanks,
    m.ananthu

    Why not SEARCH THE F*ING FORUMS!! This has been answered SO MANY TIMES

  • Execute a DOS command in java

    Hi all,
    Is it possible to execute a DOS command in java? If so, how do I do that?
    Also, if it is a Linux machine, may I execute a Linux command in java?
    Thanks for your help.
    Regards,
    Bernard

    First, define 'command'.
    You can run external programs with Runtime.exec (eg. Runtime.getRuntime().exec("notepad");) but there are a few drawbacks regarding that method.
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html

  • Running cmd commands through java

    Hi,
    I am trying to run few dos commands through java using Runtime.exec("command") but I am getting following error
    commmand is cd D:\CodeMerge\A\
    java.io.IOException: CreateProcess: cd.. error=2
    at java.lang.Win32Process.create(Native Method)
    at java.lang.Win32Process.<init>(Unknown Source)
    at java.lang.Runtime.execInternal(Native Method)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at createDirectory.main(createDirectory.java:24)
    Basically what I am looking for is this:
    1) My program is in D:\Amit\RM
    2) I want to get out to D:\ go to CodeMerge\A\.
    3) Create folder with curretn date as name of the folder
    Hence I am doing
    rTime.exec("cd../..");
    rTime.exec("cd D:\CodeMerge\A\");
    rTime.exec("mkdir "+date);
    Can anybody tell me why I am getting this error
    Jounty

    U can run either DOS Commands or UNIX Commands thru the following Java Program
    Written By BalaNagaraju Malisetti
    contact: [email protected]
    import java.io.*;
    public class RunBdiff
    public static String rununixcmd(String v_prev_path,String v_curr_path,String v_delta_path,String v_beg,String v_len)
    String s = null;
    FileOutputStream fos;
    DataOutputStream dos;
    try
    int v_int_beg = Integer.parseInt(v_beg);
    int v_int_len=Integer.parseInt(v_len);
    int v_int_end=(v_int_beg+v_int_len)-1;
    String v_pos1=String.valueOf((v_int_beg+2));
    String v_pos2=String.valueOf((v_int_end+2));
    String cmd1 = "bdiff ";
    String cmd2=v_prev_path;
    String cmd3=" ";
    String cmd4=v_curr_path;
    String cmd5="| grep '^>'";
    String cmd6="| cut -c";
    String cmd7=v_pos1+"-"+v_pos2;
    String cmd8="| sort ";
    String cmd9="| uniq ";
    String cmd=cmd1+cmd2+cmd3+cmd4+cmd5+cmd6+cmd7+cmd8+cmd9;
    String[] commands = {"/bin/csh","-c",cmd}; //in Unix
    //String[] commands = {"cmd.exe","-c",cmd}; //in Windows
    Process p = Runtime.getRuntime().exec(commands);
    BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
    BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
    // read the output from the command
    File file = new File(v_delta_path);
    fos = new FileOutputStream(file);
    dos=new DataOutputStream(fos);
    //Writing the output of bdiff command to Delta File
    while ((s = stdInput.readLine()) != null)
    dos.writeChars(s);
    //Return Error Message to Calling Procedure
    while ((s = stdError.readLine()) != null)
    return s;
    return s;
    catch (IOException e)
    return String.valueOf(e);
    public static void main(String args[])
    String msg=rununixcmd("/home/g_anil/MS_ADDRESS1.dat","/home/g_anil/MS_ADDRESS2.dat","/home/g_anil/MS_ADDRESS_DELTA.dat","1","9");
    **************************************************************************************************************************************

  • Run Command through Java Program.

    I am giving ping command in exec method of Runtime().
    But ping syntax is different for linux and windows. So when I run command on windows it wasn't worked. I am giving command --> ping -c5 ipaddress . This works fine for linux but in windows, there is no -c option. So is there any solution to overcome this situation?
    please reply ASAP.
    Thanks,
    Raj

    I am writing code that runs ping command on all OS.
    Ping syntax different for different OS (like
    windows,linux,solaris etc).
    I don't want to check for each OS and run command
    specific to that OS.
    I want to write a generic program so ping command
    execute regardless of which OS. This is self-contradictory. You can't use one command line string on different platforms if they don't support this one command string.
    The ping command is different (concretely, this -c option you mention is indeed not supported on Windows - what does it do anyway?) on different OS.
    So, you basically have two options:
    - You use only a subset of the ping options, one that does run on all your platforms (I actually expect ping to be pretty portable anyway but...).
    - Or you do use platform specific options like -c, in which case there's no way around checking the running OS and generating a specific command line.
    Can I use system calls in my program to execute the
    ping command, If yes, how?Rephrase please.

Maybe you are looking for

  • Different Audio Conflicting

    Hi, On my HP Pavilion g series, I've been having trouble with my sound. Whenever I run the voice communication apps Skype or Mumble, they seem to "take over" my headset, and all of the other audio plays through my speakers (YouTube, web browser, game

  • Assigning access for combinations of dimension members

    Security Dilemma Example                Two Dimensions: Site and Department                     Site Members     Department Members           Site A     Dept 1           Site B     Dept 2           Site C     Dept 3      Question: Is it possible in B

  • Publish To Portal Error

    Hi All, I have a problem Publishing web templates or reports from Report Designer from BI to portal. Portal has been configured.Has both ABAP+JAVA stack.I use BI7. When I do Pubilsh - >To portal in web templates or report designer (I have tried only

  • Sproxy check error , support pack 12  .

    Hi Experts! Recently support pack 12 was applied in our land scape , and after that we have observed an error , while doing a check for the proxy on the first screen of  transaction sproxy. When we check the proxy code its fine and the check for it i

  • Production CS3 and Final Cut Studio 2..

    Will both of thos programs work on a Macbook Pro, 4 GB Ram, 200 @ 7,200 RPM?? Thanks