0

Hi i tried to execute the following command from java code in linux, ls > out.txt

here is my code

try 
            { 
                Process p=Runtime.getRuntime().exec("ls > out.txt"); 
                p.waitFor(); 
                BufferedReader reader=new BufferedReader(new InputStreamReader(p.getInputStream())); 
                String line=reader.readLine(); 
                while(line!=null) 
                { 
                System.out.println(line); 
                line=reader.readLine(); 
                } 

            } 
            catch(IOException e1) {} 
            catch(InterruptedException e2) {} 

            System.out.println("Done"); 

I checked output file was not generated. However if I leave the output file part only run ls command it successfully executes without error and I can see the output.

11
  • Try e1.printStackTrace() to see if any exception is occuring. Commented Oct 16, 2012 at 3:59
  • Where do you expect the output file to be created? Do you have write access to the directory where the file is to be created? Did you try specifying an absolute path to the output file? Commented Oct 16, 2012 at 4:06
  • 1
    Nice error handling. Also you should output the process's ErrorStream so as to see any errors generated by the OS. Also, you may need to invoke the operating system's command interpreter when making system or shell command calls. Commented Oct 16, 2012 at 4:07
  • 1
    In my tests, it seems that it didn't like the redirection modifier Commented Oct 16, 2012 at 4:10
  • 1
    @pbasak: please show your final fix as an edit to your original question or as an answer to your question. For the sake of future readers of this question, please add reasonable error handling, please make sure you are reading the displaying the error stream as well. Commented Oct 16, 2012 at 12:03

2 Answers 2

1

I think it's because the pipe character > is a shell operator and your exec isn't being created with a shell.

Maybe what you are trying to do is more complex but for listing the directory you can just use a File. Then you can iterate those and save them to a file using a PrintWriter.

File dir = new File("/some/path");
PrintWriter writer = new PrintWriter("output.txt");
for(File file : dir.listFiles()){
   writer.println(file.getPath());
}
writer.close();
Sign up to request clarification or add additional context in comments.

1 Comment

Hi this is not what I am looking fo, I am just giving an example.
0

What i did is that I opened a new terminal with specific command, in this way I can handle commands whose output will be a continuous stream of events, like adb logcat of android. I did it according to this tutorial. Linux users will find something similar to this.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.