0

I'm new to Java. I want to use a command

"ps -e > /home/root/workspace/MyProject/ProcessList.txt" 

with runTime.exec();

On searching through the web, I came to know that runTime.exec() doesn't support pipes or redirecting. Please let me know how can I execute this command with my Java code. Please give exact answers.

Ingila Ejaz
  • 399
  • 7
  • 25

2 Answers2

1

Pipes and redirection are features provided by the shell. The easy (and dirty) solution is to spawn the command inside a shell: "/bin/sh -c 'ps -e > /home/root/workspace/MyProject/ProcessList.txt'".

Edit: I had forgotten that the default StringTokenizer does not work with quoted strings. Provide arguments as an array of strings.

String[] args = {
    "/bin/sh",
    "-c",
    "ps -e > /home/root/workspace/MyProject/ProcessList.txt"
};
java.lang.Runtime.getRuntime(args);
kmkaplan
  • 18,655
  • 4
  • 51
  • 65
0

You could take a look at this question: Input and Output Stream Pipe in Java

Otherwise, if you know you are on a platform that supports the bourne shell (sh), you could add that to the command to run the original command in that shell:

"sh -c 'ps -e > /home/root/workspace/MyProject/ProcessList.txt'"

Community
  • 1
  • 1
Victor Zamanian
  • 3,100
  • 24
  • 31