1

I want to redirect the output to text file using Runtime.getRuntime().exec("ls > 1.txt") but it doesn't work. I tried by passing string array instead of string but it didn't work.Other commands such as opening open is working fine.

Is there any solution to redirect the output to a text file.

1 Answers1

2

Using Runtime.exec() is bad practice, you should use a ProcessBuilder.
ProcessBuilder has a .redirectOutput() method which enables you to define where you want to receive the process' output.

Aaron
  • 24,009
  • 2
  • 33
  • 57
  • Thanks for the suggestion. Is there any method to append the data to the existing file like using ">>" ? –  Apr 28 '16 at 13:44
  • Yes there is : the `.redirectOutput()` expects a `ProcessBuilder.Redirect`, which can be either `ProcessBuilder.Redirect.to(File f)`, overwriting the file, or `ProcessBuilder.Redirect.appendTo(File f)` where it will append as would `>>` – Aaron Apr 28 '16 at 13:46