【发布时间】:2014-01-30 13:06:34
【问题描述】:
好的,我们开始: 当我通过静态 main 传递参数时,我的程序运行良好。但是当我通过在 main 中声明的相同“参数”时,它不起作用。如果听起来很困惑,这里是代码。我想要做的就是通过 main 不带 args 来做这些事情。 这是调试:http://i.stack.imgur.com/sbGyo.png
import java.io.*;
import java.util.*;
public class DoProcessBuilder extends Thread {
public static void main (String[] args) throws IOException, InterruptedException {
DoProcessBuilder teste = new DoProcessBuilder();
String[] uia = {"ls","-al","|","grep","bash"};
teste.ExecCommand(uia); // here this not works, WHY? if I execute the "java DoProcessBuilder ls -al | grep bash" works fine?
teste.ExecCommand(args); // works fine!
}
public String ExecCommand(String args[]) throws IOException, InterruptedException {
StringBuffer x = new StringBuffer();
if (args.length <= 0) {
System.err.println("Need command to run");
}
Process process = new ProcessBuilder(args).start();
process.waitFor();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = "";
while((line = br.readLine()) != null){
x.append(line+"\n");
}
System.out.println("\nCOMMAND OUT \n"+x.toString());
return x.toString();
}
}
【问题讨论】:
-
请告诉我们您的堆栈跟踪“不起作用”对我们没有帮助
-
它应该可以工作。就像 Philipp 说的,请发布堆栈跟踪。
-
打印两个数组并检查它们是否相等
-
根据给定的信息,我只能说
uia和args不包含完全相同的字符串。使用断点来验证这一点。 -
这是一个练习还是你真的想使用它?使用外部命令不是java的做事方式!几乎从来没有调用外部命令的冲动。对于给定的任务,您可以使用 File#listFiles() 并过滤接收到的文件列表。