Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/blackberry/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
了解Java中processbuilder的示例代码_Java_Processbuilder - Fatal编程技术网

了解Java中processbuilder的示例代码

了解Java中processbuilder的示例代码,java,processbuilder,Java,Processbuilder,我有一些示例代码,其中使用了process builder并给出了两个要执行的命令,但我不能完全理解每行代码都在做什么 此外,这些命令似乎没有实际执行 代码: publicstaticvoidmain(字符串[]args){ ArrayList commands=new ArrayList();//processbuilder中的命令是字符串的ArrayList commands.add(“myfile.pdf”);//应该打开文件吗? commands.add(“bash\”,\“-c\”,\

我有一些示例代码,其中使用了process builder并给出了两个要执行的命令,但我不能完全理解每行代码都在做什么

此外,这些命令似乎没有实际执行

代码:

publicstaticvoidmain(字符串[]args){
ArrayList commands=new ArrayList();//processbuilder中的命令是字符串的ArrayList
commands.add(“myfile.pdf”);//应该打开文件吗?
commands.add(“bash\”,\“-c\”,\“ls”);//应该在终端中使用ls命令
execute(commands);//应该执行上面的两个命令
System.out.println(“已执行的命令”);//唯一实际发生的事情
}
公共静态void execute(ArrayList命令){
试一试{
ProcessBuilder=new ProcessBuilder(command);//一个新的生成器,它接受传递到方法中的命令
映射环境=builder.environment();/???
进程p=builder.start();//从未使用过p吗?
}捕获(例外e){
e、 printStackTrace();
}
}
我没有收到任何错误或警告


尝试在processbuilder上阅读API,但我并不真正理解它有助于启动外部进程

首先,命令行部分(可执行文件、参数)被视为
字符串的列表,这非常方便。(“
命令
”在这里有点误导,因为它由可执行文件和参数组成)

其次,您可以编辑新流程的环境(环境变量,如“
$HOME
”、“
$PATH
”等)

您的
p
可用于检查流程是否已完成,或检索新流程的输入/输出。因为你只需要启动这个过程(开火然后忘记),所以这里不需要它

您也可以使用
Runtime.exec(…)
来启动外部进程,这是一种历史性的启动方式,但我认为使用
ProcessBuilder
更方便

public static void main(String[] args) {

    ArrayList<String> commands = new ArrayList(); // commands in a processbuilder is an Arraylist of of strings
    commands.add("myfile.pdf"); // supposed to open the file?
    commands.add("bash\", \"-c\", \"ls"); // supposed to use ls command in terminal
    execute(commands); // should execute the two commands above
    System.out.println("executed commands"); // only thing that actually happens
}

public static void execute(ArrayList<String> command) {
    try {
        ProcessBuilder builder = new ProcessBuilder(command); // a new builder which takes a command passed into the method
        Map<String, String> environ = builder.environment(); // ???
        Process p = builder.start(); // p is never used?
    } catch (Exception e) {
        e.printStackTrace();
    }
}