Results 1 to 2 of 2
  1. #1
    swapnilnawale is offline Member
    Join Date
    Mar 2009
    Posts
    2
    Rep Power
    0

    Default Problem with Runtime.getRuntime().exec with Linux Commands

    Hi All ,

    I am writing a Java program which will basically copy the filenames starting with "C" to a txt file.This program will be executed on Linux OS.

    I can do it with normal Linux Command :
    Java Code:
     ls C* >> abc.txt
    This command creates abc.txt containing list of filenames starting with "C"

    But when I try to execute above command with Runtime.getRuntime().exec,the file abc.txt is not created.

    Below is the code :

    Java Code:
    import java.io.*;  
    public class TestExec {  
    public static void main(String[] args){  
    	try {  
              	Process p = Runtime.getRuntime().exec("ls C* >> abc.txt");  
                    BufferedReader in = new BufferedReader(  
                                        new InputStreamReader(p.getInputStream()));  
                    String line = null;  
                    while ((line = in.readLine()) != null) {  
                       System.out.println(line);  
                   }  
               } catch (IOException e) {  
                   e.printStackTrace();  
               }  
           }
    }
    I have even tried following call for shell invocation , but no success :(
    Java Code:
    Process p = Runtime.getRuntime().exec("/bin/bash -c 'ls C* >> abc.txt'");
    Can anyone suggest way to solve above problem or any workaround approach ?

  2. #2
    Mr.Beans's Avatar
    Mr.Beans is offline Senior Member
    Join Date
    Apr 2009
    Location
    Virginia Beach, Virginia
    Posts
    149
    Rep Power
    0

    Default

    Maybe try reading the stream from java
    Java Code:
    Process process=Runtime.getRuntime().exec("/bin/bash -c ls C*");
    BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
    However, if all your trying to do is list files that start with 'C', you may want to use the java api to find and list the files as it would work on multiple platforms (ie BSD, Mac, etc).
    Last edited by Mr.Beans; 09-23-2009 at 11:27 PM.

Similar Threads

  1. Replies: 3
    Last Post: 04-02-2009, 09:16 PM
  2. grep on multiple files using Runtime.getRuntime().exec()
    By cprash.aggarwal in forum Advanced Java
    Replies: 3
    Last Post: 02-11-2009, 07:55 AM
  3. Replies: 6
    Last Post: 12-29-2008, 03:47 PM
  4. linux generic Exec command...???
    By nlgopi in forum Advanced Java
    Replies: 5
    Last Post: 10-08-2008, 08:08 PM
  5. Problem with Runtime.exec()
    By nhabibi in forum Advanced Java
    Replies: 11
    Last Post: 07-02-2008, 02:35 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •