main(String [] args)不同的String [] args = {.....}?

时间:2014-01-30 13:06:34

标签: java main args

好的,我们走了: 当我通过static main传递参数时,我的程序运行正常。但是,当我传递相同的“论点”在主要内部声明时,不起作用。如果声音混乱,这是代码。我想要的只是做这些事情,没有args通过main。 这是DEBUG: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();

  }
}

2 个答案:

答案 0 :(得分:2)

您正在尝试使用ProcessBuilder执行shell管道。那不行。管道|不是ls命令的有效参数。您必须启动一个shell new ProcessBUilder("sh")

它与args一起工作正常,因为你的程序没有得到管道,其余来自调用shell。您的计划只获得ls -al

答案 1 :(得分:0)

没有问题,你提到的地方。但是使用teste.ExecCommand(args);,您将获得ArrayIndexOutOfBoundsException

   StringBuffer x = new StringBuffer();
    if (args.length <= 0) {
        System.err.println("Need command to run");
    }

    Process process = new ProcessBuilder(args).start(); // ArrayIndexOutOfBoundsException
    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();