简体   繁体   English

如何通过runTime.exec()使用涉及“>”的linux命令

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

I'm new to Java. 我是Java新手。 I want to use a command 我想使用命令

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

with runTime.exec(); 与runTime.exec();

On searching through the web, I came to know that runTime.exec() doesn't support pipes or redirecting. 在网上搜索时,我知道runTime.exec()不支持管道或重定向。 Please let me know how can I execute this command with my Java code. 请让我知道如何使用我的Java代码执行此命令。 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'" . 一种简单(又脏)的解决方案是在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. 编辑:我忘记了默认的StringTokenizer不适用于带引号的字符串。 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 您可以看一下这个问题: 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: 否则,如果您知道自己所处的平台支持bourne shell( sh ),则可以将其添加到命令中以在该shell中运行原始命令:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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