为什么shell脚本不会从Java Runtime.exec执行,而是从命令行执行?
希望有人能帮我。谷歌搜索,直到我的眼睛流血,没有运气,并尝试了一切我能想到的 我正在尝试执行一个播放歌曲的shell脚本。在命令行中键入以下内容时,一切正常: /home/pi/startsong.sh/path/to/track 但是,我试图通过Java应用程序执行脚本,但没有得到任何响应。以下是我正在做的:为什么shell脚本不会从Java Runtime.exec执行,而是从命令行执行?,java,linux,bash,shell,Java,Linux,Bash,Shell,希望有人能帮我。谷歌搜索,直到我的眼睛流血,没有运气,并尝试了一切我能想到的 我正在尝试执行一个播放歌曲的shell脚本。在命令行中键入以下内容时,一切正常: /home/pi/startsong.sh/path/to/track 但是,我试图通过Java应用程序执行脚本,但没有得到任何响应。以下是我正在做的: public void begin(String song) throws IOException, InterruptedException { //Split song t
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添加到命令字符串的开头
仅供参考,我在运行Raspbian的Raspberry Pi上运行Java 8。播放曲目的程序是omxplayer
非常感谢您的帮助,因为我一整天都在忙这个
谢谢 好的,多亏@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!");
}
您可以在相同的硬件上以相同的用户身份正确运行该功能,因为您尝试在/as上运行java应用程序?您已经尝试以sudo的身份运行应用程序和shell脚本,没有更改:/n这并不能直接回答问题。您是否以与java应用程序相同的用户和硬件手动尝试过该脚本?你试过的时候有用吗?当您从java运行脚本时,脚本是否输出任何错误/等?对不起,我不理解这个问题。是的,当我以与Java应用程序相同的用户和硬件运行它时,脚本就会运行。为清楚起见,我在Netbeans中编写代码,但在RPi上测试并运行,因此执行总是由同一用户和硬件执行。抱歉。不过,你已经让我找到了正确的答案。我发现了一种通过添加InputStream读取器从bash脚本中获取错误的方法。这告诉我文件名传递不正确。非常感谢您的时间和帮助!