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

Similar Messages

  • Executing a command by Runtime.getRuntime.exec().

    Hi,
    I am try to run a java command from one java program. Is it possible
    eg :
    public class A {
    public static void main(String[] args) {
    String startjvm ="java -classpath E:\classes B";
    Runtime.getRuntime.exec(startjvm);
    public class B {
    public static void main(String[] args) {
    System.out.println("Inside the main for class B");
    when i execute the above command from the command line it executes,but when are run the main method for class A nothing happens meaning the message : "Inside the main for class B" is not displayed.
    I also tried displaying the int returned by process.waitfor() method. process is the object returned by the Runtime.getRuntime.exec() method. The int returned is 0 which means the process terminated previously.
    Thanks in advance

    You could get InputStream from created Process and read
    information from it.
    For example
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    public class A {
        public static void main(String[] args) {
            try{
                String startjvm ="java -classpath E:\\classes B";
                Process s = Runtime.getRuntime().exec(startjvm);
                BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
                String line = "";
                while ((line = in.readLine()) != null) {
                    System.out.println(line);
                in.close();
            }catch(Exception e){
                e.printStackTrace();
        }

  • 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

  • Error while Executing Unix Shell Commands Using Runtime clas

    I am trying to run the following code in java on unix machine to execute cat command.
    Runtime runtime = Runtime.getRuntime();
              try {
                   System.out.println("before catexecute");
                   Process process = runtime.exec("cat /export/home/shankerr/local.profile > /export/home/shankerr/local1.txt");
                   try {
                        if (process.waitFor() != 0) {
                        System.err.println("exit value = " +
                                  process.exitValue());
                        catch (InterruptedException e) {
                        System.err.println(e);
    But i get the following error on the console
    exit value = 2
    cat: cannot open >
    cat: cannot open /export/home/shankerr/local1.txt
    The same command if i run on unix console directly it creates a new file and copies the content into the new file local1.txt
    kindly help me on the same

    The redirection operator > along with stuff like pipe | history !$ etc. is interpreted by the shell, not by the cat program.
    When you do cat X > Ycat only sees the X. The rest is interpreted by the shell to redirect the cat program's stdout.
    However, when you Runtime.exec(), you don't have the shell, so cat sees X > Y as its arguments, and interprets them all as file names. Since there's no file named > you get the error.
    The solution is to first man cat on your system and see if it happens to have a -o or somesuch operator that lets it (rather than the shell) send its output to a file. If not, then you need to invoke a shell, and pass it cat and all of cat's args as the command to execute.
    Read the man pages for you shell of choice, but for bash, I believe you'd give Runtime.exec() something like /bin/bash -c 'cat X > Y'

  • Running commands from the Command Prompt -  Runtime.getRuntime().exec()

    Hi there,
    I'm already able to run several commands in the command prompt.
    But my problem is that I need all the commands that I run share the same context.
    If, for example, I run "cmd /c set HOME=C:" (1st command), I want to be able to access that variable the next time, so that later when I run "dir %home%" it shows the directories in c: (This is just a example this is not what I really want to do...)
    I used code posted in a newsgroup (don't remember which)
    This is the code I use to execute commands:
         private int execute(String command)
         int exitVal = 0;
    try
    String nomeOS = System.getProperty("os.name" );
    String[] cmd = new String[3];
    if( nomeOS.equals( "Windows NT" ) || nomeOS.equals("Windows 2000") )
    cmd[0]="cmd.exe";
    cmd[1]="/c";
    cmd[2]=command;
    else if( nomeOS.equals( "Windows 95" ) )
    cmd[0]="command.com";
    cmd[1]="/c";
    cmd[2]=command;
    if (rt==null)
         rt = Runtime.getRuntime();
              Process proc = rt.exec(cmd);
              CommandStream erro = null;
              // erros?
              if (proc.getErrorStream()!=null)
                   erro = new CommandStream(proc.getErrorStream());
                   erro.start();
    // output?
    CommandStream output = new
    CommandStream(proc.getInputStream());
    // arranque
    output.start();
    // erros???
    exitVal = proc.waitFor();
         } catch (IOException e)
                   System.out.println("Exce !!!" );
                   e.printStackTrace();
         catch (InterruptedException ie)
                   System.out.println("Ocorreu uma excep��o !!!" );
                   ie.printStackTrace();
    return exitVal;      

    My problem is bigger than setting a few parameters,
    I'm doing a GUI to a CVS client and the problem is that some commands of CVS only work if you're in the right directory, or if you're authenticated, and all of this is easily done doing a series of execution:
    In a command prompt opened I would:
    set cvsroot=:pserver:lpinho@w2palf38:/project
    cvs -d :pserver:lpinho:xxxxx@w2palf38:/project login
    mkdir temp_my_proj
    cd temp_my_proj
    cvs checkout my_projectAll this would make what I wanted...
    And there's another thing, when I set the envp, I get some errors like "cvs.exe is not recognized as an internal or external command" (the path went bye bye) and if I set the path (envp[0]="path=c:\cvsnt"), I'm able to run cvs but I get a crazy error "No such host is known" (I run exactly the same command in the command prompt and it works...)
    Do you know any way of getting the current environment, and pass it as the envp parameter?
    Thank You
    Luis Pinho

  • Need to run two commands in Runtime.getRuntime.exec()???

    I need to run two commands in the same shell , in the same exec function... is this possible? I tried to invoke
    ksh -e ... command1;command2
    but that did nothing

    I need to run two commands in the same shell , in the
    same exec function... is this possible? I tried to
    invoke
    ksh -e ... command1;command2
    but that did nothingI'm not all that familiar with that particular shell (ksh), but if it works from the command-line, I'd venture to guess that it would have worked there as well. My guess is it did "work" (executed the 2 commands) but that you may have misdiagnosed the real problem (current working directory assumption incorrect, etc).

  • Runtime.getRuntime().exec() error message "cannot execute"

    I'm trying to start another program written in c++ with the commands:
    p=Runtime.getRuntime().exec("nameofmyprogram");
    it works with other programs written in java, and also with ordinary unixcommands like "ls" etc. but when I try to start the c++-one I get the message: cannot execute.
    I can start the program directly from the terminal window, so it's ok.
    does anybody have any idea of what I'm doing wrong?
    ( my friend claims that it has to have a name ending with .exe, is that true?)
    grateful for advice!

    My first guess would be that the program is not on the path and Java cannot find the executable, ls on the other hand is on the path..
    I'm assuming that you are running on a unix system as you are using ls, so in this case your program does not need to end in exe, this is a windows thing. If your C++ program compiled on windows it would end in exe, but this is not the case on unix systems.
    I would suggest you try either giving the exec method ./nameofmyprogram assuming java is working in the directory your compiled c++ program. The other is to give the exact location.

  • Problems running Runtime.getRuntime().exec(path)

    I am trying to run the following command, so that i can execute a file on DOS
    Runtime.getRuntime().exec(path);
    where
    path = cmd /c C:\Dokumente und Einstellungen\Administrator\Lokale Einstellungen\Temp\muexec2562.bat
    (btw i think /c is german notoation used for -c). all i get is the DOS screen briefly popping up on screen and then disappearing. The .bat files contains commands to copy files.
    Thanks

    Replace your path with
    path = C:\Dokumente und Einstellungen\Administrator\Lokale Einstellungen\Temp\muexec2562.bat

  • Runtime.getRuntime().exec problem with linux script.

    Hello,
    I try to start a script under Linux RedHat 9. This script must just create another file.
    I work with JDK 1.4.1_02b06.
    If I use the next command
    process = Runtime.getRuntime().exec("/temp/myScript.sh");
    This is not working. I script file is existing otherwise I receive an error. I don't understand why the script is not executed!
    I have check some other posts in this forum but I cannot find the solution.
    Thanks in advance for your help.
    Alain.

    Try running it with sh: Runtime.getRuntime().exec("sh /temp/myScript.sh");

  • Runtime.getRuntime().exec()  unix shell

    When I try to run commands like Runtime.getRuntime().exec("ls *")
    I got null returned buffer
    If I use commands like Runtime.getRuntime().exec("ls file.dat")
    i got the right details
    Anybody know why it happens???
    Thanks

    Input-output redirection, filename wild-card-expansion, metacharacter evaluation etc. are performed by the command shell.
    You should try String [] {"sh","-c","ls","*"}

  • Runtime.getRuntime().exec works on windows failed on linux!

    Hi,
    I'm trying to execute a linux command from java 1.4.2 using Runtime.getRuntime().exec(). The linux command produces output and write to a file in my home dir. The command runs interactively in the shell and also run on windows.
    The command is actually a mozilla pk12util. My java code to run this pk12util works on windows, but not on linux (fedora). When I print out the command I'm trying to run in java, I can run it interactively in bash shell.
    Method below is where the problem seems to be:
    public void writeCert() {
    // Declaring variables
    System.out.println("Entering writeCert method");
    String command = null;
    certFile = new File(credFileName);
    // building the command for either Linux or Windows
    if (System.getProperty("os.name").equals("Linux")) {
    command = linuxPathPrefix + File.separator + "pk12util -o "
    + credFileName + " -n \"" + nickName + "\" -d "
    + dbDirectory + " -K " + slotpw + " -w " + slotpw + " -W "
    + pk12pw;
    System.out.println("System type is linux.");
    System.out.println("Command is: " + command);
    if (System.getProperty("os.name").indexOf("Windows") != -1) {
    // command = pk12utilLoc + File.separator + "pk12util -o
    // "+credFileName+" -n "\"+nickname+\"" -d \""+dbDirectory+"\" -K
    // "+pk12pw+" -w "+pk12pw+" -W "+pk12pw;
    command = pk12utilLoc + File.separator + "pk12util.exe -o "
    + credFileName + " -n \"" + nickName + "\" -d "
    + dbDirectory + " -K " + slotpw + " -w " + slotpw + " -W "
    + pk12pw;
    System.out.println("System type is windows.");
    System.out.println("Command is: " + command);
    // If the system is neither Linux or Windows, throw exception
    if (command == null) {
    System.out.println("command equals null");
    try {
    throw new Exception("Can't identify OS");
    } catch (Exception e) {
    System.out.println(e.getMessage());
    e.printStackTrace();
    // Having built the command, running it with Runtime.exec
    File f = new File(credFileName);
    // setting up process, getting readers and writers
    Process extraction = null;
    BufferedOutputStream writeCred = null;
    // executing command - note -o option does not create output
    // file, or write anything to it, for Linux
    try {
    extraction = Runtime.getRuntime().exec(command);
    } catch (IOException e) {
    System.out.println(e.getMessage());
    e.printStackTrace();
    // Dealing with the the output of the command; think -o
    // option in command should just write the credential but dealing with output anyway
    BufferedWriter CredentialOut = null;
    OutputStream line;
    try {
    CredentialOut = new BufferedWriter (
    new OutputStreamWriter(
    new FileOutputStream(credFileName)));
    catch (FileNotFoundException e) {
    System.out.println(e.getMessage());
    e.printStackTrace();
    // writing out the output; currently having problems because I am trying to run
    }

    My error is due to the nickname "-n <nickname" parameter error. I think the problem is having a double quotes around my nickname, but if I take out the double quotes around my nickname "Jana Test's ID" won't work either because there are spaces between the String. Error below:
    Command is: /usr/bin/pk12util -o jtest.p12 -n "Jana Test's Development ID" -d /home/jnguyen/.mozilla/firefox/zdpsq44v.default -K test123 -w test123 -W test123
    Read from standard outputStreamjava.io.PrintStream@19821f
    Read from error stream: "pk12util: find user certs from nickname failed: security library: bad database."
    null
    java.lang.NullPointerException
    at ExtractCert.writeCert(ExtractCert.java:260)
    at ExtractCert.main(ExtractCert.java:302)
    Code is:
    private String nickName = null;
    private void setNickname(String nicknameIn) {
    nickName = nicknameIn;
    // building the command for either Linux or Windows
    if (System.getProperty("os.name").equals("Linux")) {
    command = linuxPathPrefix + File.separator + "pk12util -o " + credFileName + " -n \"" + nickName + "\" -d " + dbDirectory + " -K " + slotpw + " -w " + slotpw + " -W " + pk12pw;
    System.out.println("System type is linux.");
    System.out.println("Command is: " + command);
    extraction = Runtime.getRuntime().exec(command);
    BufferedReader br = new BufferedReader(
    new
    InputStreamReader(extraction.getErrorStream()));
    PrintStream p = new PrintStream(extraction.getOutputStream());
    System.out.println("Read from standard outputStream" + p);

  • Runtime.getRuntime.exec(cmd) - 'out of space'

    And helpful suggestions from the Java / AIX boffins out there would be appreciated.
    System: AIX 4.3 jdk 1.3.1
    Briefly, I am attempting to invoke the ibm 'c' compiler from within a java program.
    The command:-
    p = Runtime.getRuntime.exec("/usr/ibmcxx/bin/cc test.c")
    returns the os error 'mmap failed: Not enough space'
    other commands that do work:-
    p = Runtime.getRuntime.exec("ls -l")
    return successfully without error
    p = Runtime.getRuntime.exec("/usr/ibmcxx/bin/cc Notfound.c")
    raises the error '/usr/ibmcxx/bin/cc 1501-288 input file NotFound.c not found' - as expected.
    Additionally:-
    I have tried invoking the program with the -msnnM & -mxnnM flags set to large values.
    /usr/ibmcxx/bin/cc test.c : works happily from the command line.
    cheers
    John.

    Thanks but not made any difference.
    keep those ideas coming!
    Does any body 'real' understand how the getRuntime() interacts with the underlying OS? I assume that the "mmap failed" is coming from the compiler rather then the JVM. But does it throw this error only when run through the JVM ?
    John.

  • Syntax of Runtime.getRuntime().exec()

    i hava batch file command (genXML) in directory C:\update ,this command syntax is: genXML sourceFile resultFile outputDirectory
    how can I run the command with Runtime.getRuntime().exec() ?
    Thanks

    i hava batch file command (genXML) in directory
    C:\update ,this command syntax is: genXML sourceFile
    resultFile outputDirectory
    how can I run the command with
    Runtime.getRuntime().exec() ?
    Thanksuse the
    public Process exec(String[] cmdarray)
    version of exec as follows:
    where genProg is the path and name of your genXML program
    ie. genProg = "C:\\update\\genXML.exe"
    String[] cmd = {genProg, source, results, outputDir};

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

  • Linux shell commands through linux

    i am trying to run shell comands through java.
    so far i hav been success ful in running some of them. but when ever a '\' symbol is encountered it doesnt work.
    i use
    process p = Runtime.getRuntime().exec(command)
    example
    command= "mount -t smbfs //192.168.10.150/abcd /home/lan" works fine
    but "mount -t smbfs //192.168.10.34/english\\ songs /home/lan"
    does not work
    is there a way to bypass writing a shell script and executing it?
    i just want to execute it directly without writing it in a shell file first.

    yes there are spaces in the path name thats why im using '\'. and yes in the string i do write it as '\\'. it displays the correct path name using println in the terminal but doesnt run using exec(). im aware of the temp.sh way and i know it works but im working on a networking project and want to avoid writing to a file again and again.
    the other constructor of exec seems interesting. ill try it.

Maybe you are looking for