简体   繁体   中英

How to use linux commands involving “>” through runTime.exec()

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.

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);

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'"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM