如果切断,则用Java执行Bash命令

时间:2015-03-10 17:12:00

标签: java bash command-line command

我想执行一个我写过的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脚本似乎只对命令中的第一个单词执行。

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

2 个答案:

答案 0 :(得分:1)

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

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

或者更好的是,使用ProcessBuilder

答案 1 :(得分:1)

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

  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 
  }