【问题标题】:Why will shell script not execute from Java Runtime.exec but will from command line?为什么 shell 脚本不会从 Java Runtime.exec 执行,而是从命令行执行?
【发布时间】:2014-11-17 17:53:22
【问题描述】:

希望有人可以在这里帮助我。谷歌搜索直到我的眼睛流血但没有运气,并尝试了我能想到的一切。

我正在尝试执行一个播放歌曲的 shell 脚本。当我在命令行中输入以下内容时,一切都很好: /home/pi/startsong.sh /path/to/track

但是,我正在尝试通过 Java 应用程序执行脚本,但根本没有得到任何响应。这就是我正在做的事情:

public void begin(String song) throws IOException, InterruptedException {

    //Split song title
    String[] cmd = song.split("");
    StringBuilder sb = new StringBuilder();

    //Ignore for now, this is just about sorting out titles with spaces, but irrelevant
    for (int i = 0; i < cmd.length; i++) {
        if (cmd[i].equals(" ")) {
            cmd[i] = " ";
        }
        sb.append(cmd[i]);
    }

    //Initiate bash script whilst passing song title as argument
    String command = "/home/pi/startsong.sh " + sb.toString();
    System.out.println(command);
    Runtime rt = Runtime.getRuntime();
    Process p = rt.exec(command);
    p.waitFor();
    System.out.println("Playing song...");

}

当我运行程序时,它打印的命令(正如我要求的那样)与我在命令行中输入的命令完全相同。

为什么脚本不执行?

我尝试过使用ProcessBuilder 并调用直接播放曲目的程序,但都不起作用。为简单起见,我使用路径没有空格或奇怪字符的轨道进行测试。

我尝试将/bin/bash -c 添加到command 字符串的开头

仅供参考,我在运行 Raspbian 的 Raspberry Pi 上运行 Java 8。播放曲目的程序是omxplayer。

任何帮助都非常感激,因为我整天都在做这件事!

谢谢!

【问题讨论】:

  • 您可以在相同的硬件上以相同的用户身份正确运行它吗?就像您尝试在/as 上运行 java 应用程序一样?
  • 已尝试将应用程序和 shell 脚本作为 sudo 运行,没有变化:/
  • 这并不能直接回答问题。您是否以与 Java 应用程序相同的用户和相同的硬件手动尝试了该脚本?当你尝试的时候它有效吗?脚本是否输出任何错误/等。当你从 java 运行它时?
  • 抱歉,没看懂问题。是的,当我以同一用户身份运行脚本并以 Java 应用程序运行时,该脚本运行。为清楚起见,我在 Netbeans 中编写代码,但在 RPi 上进行测试和运行,因此始终使用相同的用户和硬件执行。道歉。
  • 但是,您已经引导我找到正确的答案。我找到了一种通过添加 InputStream 阅读器从 bash 脚本中获取错误的方法。这告诉我文件名没有正确传递。非常感谢您的时间和帮助!

标签: java linux bash shell


【解决方案1】:

好的,感谢@Etan,我设法解决了这个问题。因此修改了代码,使用 InputStream 阅读器来识别文件名问题:

public void begin(String song) throws IOException, InterruptedException {

    //Split song title
    String[] cmd = song.split("");
    StringBuilder sb = new StringBuilder();

    //Ignore for now
    for (int i = 0; i < cmd.length; i++) {
        if (cmd[i].equals(" ")) {
            cmd[i] = " ";
        }
        sb.append(cmd[i]);
    }

    //Initiate bash script whilst passing song title as argument

    System.out.println("Playing song...");

    ProcessBuilder pb = new ProcessBuilder("/bin/bash", "/home/pi/startsong.sh", "/home"+sb.toString());
    final Process process = pb.start();

    InputStream is = process.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);
    String line;

    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
    System.out.println("Program terminated!");

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-30
    • 1970-01-01
    • 2011-03-04
    • 1970-01-01
    • 2018-02-27
    • 2018-03-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多