我有一个我想从java运行的shell脚本文件。我的java工作空间目录与脚本的目录不同。
private final String scriptPath = "/home/kemallin/Desktop/";
public void cleanCSVScript() {
String script = "clean.sh";
try {
Process awk = new ProcessBuilder(scriptPath + script).start();
awk.waitFor();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
我收到此错误:
java.io.IOException: Cannot run program "cat /home/kemallin/Desktop/capture-03.csv | awk -F ',' '{ print $1,",", $2,",", $3,",", $4,",", $6}' > clean.csv": error=2, No such file or directory
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1047)
at ShellScript.cleanCSVScript(ShellScript.java:21)
at Main.main(Main.java:15)
Caused by: java.io.IOException: error=2, No such file or directory
at java.lang.UNIXProcess.forkAndExec(Native Method)
at java.lang.UNIXProcess.<init>(UNIXProcess.java:186)
at java.lang.ProcessImpl.start(ProcessImpl.java:130)
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1028)
... 2 more
java.io.FileNotFoundException: /home/kemallin/Desktop/clean.csv (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:146)
at java.io.FileInputStream.<init>(FileInputStream.java:101)
at java.io.FileReader.<init>(FileReader.java:58)
at CSVReader.run(CSVReader.java:25)
at Main.main(Main.java:17)
我用Google搜索过,每个解决方案都表明我做的是正确的事。
我试图将脚本文件放在src和Java项目的bin中,但它仍然没有说这样的文件或目录。
我做错了什么?
感谢。
答案 0 :(得分:13)
您的程序clean.sh
不是Java可以理解的,即使底层系统将其理解为可执行文件。
您需要告诉Java执行命令需要哪些shell。做(假设您使用的是bash
并且安装在/bin/bash
):
private final String scriptPath = "/home/kemallin/Desktop/";
public void cleanCSVScript() {
String script = "clean.sh";
try {
Process awk = new ProcessBuilder("/bin/bash", scriptPath + script).start();
awk.waitFor();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
答案 1 :(得分:1)
您应该执行chmod 755 /home/kemallin/Desktop/clean.sh
并确保java进程在相同的用户标识