【问题标题】:Bash command executed in Java if cuttoff如果切断,则在 Java 中执行 Bash 命令
【发布时间】:2015-05-12 06:13:34
【问题描述】:

我想执行我编写的 bash 脚本,但它似乎在执行过程中被切断。

脚本是:

#!/bin/bash
pico2wave -w=tmp/temp.wav "$1"
aplay tmp/temp.wav
rm tmp/temp.wav

Java 代码是:

String command = "bash vox '" + text + "'";
System.out.println(command);
Runtime.getRuntime().exec(command);

如果变量text = "Hello World",程序打印:

 bash vox 'Hello World'

但是 bash 脚本似乎只针对命令中的第一个单词执行。

当我在终端中执行命令时,它按预期工作。

【问题讨论】:

    标签: java bash command-line command


    【解决方案1】:

    您尝试使用单引号失败。实际上,Java 已经在空格处分割字符串(或者更确切地说,using a StringTokenizer),而不是 shell,所以引号不起作用。相反,请尝试使用

    Runtime.getRuntime().exec(new String[] { "bash", "vox", text });
    

    或者更好的是,使用ProcessBuilder

    【讨论】:

    • 奇怪的是,我的 IDE 告诉我:未闭合字符文字,未闭合字符文字,不是语句,未闭合字符文字,未闭合字符文字,不是语句,';'预期,而不是陈述。
    • 谢谢 - 我的代码中有一个缺失/错误的引用,它不是一个数组,因为它应该是......总是在发布之前编译东西,抱歉。感谢@that other guy。
    • 我已经通过将参数作为字符串数组传递来使其工作。感谢您的提示!
    【解决方案2】:

    最好的方法是使用流程构建器。这是一个例子:

      ArrayList<String> listCommands = new ArrayList<String>();
      // Optional for opening a new command window, useful for the output of the tool you started, uncomment to use
      // the problem with this is that "waitFor()" (see below) will return immediatialy without waiting for the tool you started
      //listCommands.add("cmd");
      //listCommands.add("/c");
      // listCommands.add("start");
    
      listCommands.add(bash);
      listCommands.add(vox);
      // path
      String text = <your text>
      if (text .contains(" ")) {
           text = "\"" + text + "\"";
      }
      listCommands.add(text );
    
      // add more parameters if you need them here
    
      String[] cmd = new String[listCommands.size()];
      for (int i = 0; i < listCommands.size(); i++) {
           cmd[i] = listCommands.get(i);
      }
      ProcessBuilder pb = new ProcessBuilder(cmd);
      //  optional execution directory, uncomment to use
      // pb.directory(new java.io.File(pathOut));
      Process p = pb.start();
      try {
          // waits till the process is finished, delete if you don't need it
            p.waitFor();
      } catch (InterruptedException ex) {
           // here your code 
      }
    

    【讨论】:

    • 你把文字和名字混为一谈,但正确的做事方式
    • 谢谢,这是我自己的代码,我忘记了要替换的东西
    猜你喜欢
    • 1970-01-01
    • 2011-12-22
    • 2016-11-26
    • 2017-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-30
    相关资源
    最近更新 更多