在Linux中,我正在尝试使用Java的Runtime.getRuntime().exec()来执行git clone,解释器是/bin/bash。但是,我在错误流中得到“没有这样的文件或目录”。我搜索了堆栈溢出,发现没有答案可以解决我的问题。下面是我用Test.java编写的程序:
import java.io.*;
public class Test {
public static void main(String[] args) throws IOException, InterruptedException {
String version = "10.1.1";
String repo_url = "https://github.com/postcss/postcss-url";
String directory = "./tmp";
String cmd = "\"/usr/bin/git clone --branch " + version + " " + repo_url + " --depth=1 " + directory + "\"";
// String cmd = "git -h";
String interpreter = "/bin/bash";
cmd = " -c "+ cmd;
System.out.println(interpreter + cmd);
Process process = Runtime.getRuntime().exec(new String[]{ interpreter, cmd });
print(process.getInputStream());
print(process.getErrorStream());
process.waitFor();
int exitStatus = process.exitValue();
System.out.println("exit status: " + exitStatus);
File[] files = new File(directory).listFiles();
System.out.println("number of files in the directory: " + files.length);
}
public static void print(InputStream input) {
new Thread(new Runnable() {
@Override
public void run() {
BufferedReader bf = new BufferedReader(new InputStreamReader(input));
String line = null;
try {
while ((line = bf.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("IOException");
}
}
}).start();
}
}./tmp肯定是一个空目录。我使用javac Test.java编译代码,然后运行java Test。此外,我尝试了sudo java Test,得到了同样的结果。我得到的输出如下:
/bin/bash -c "/usr/bin/git clone --branch 10.1.1 https://github.com/postcss/postcss-url --depth=1 ./tmp"
exit status: 127
/bin/bash: -c "/usr/bin/git clone --branch 10.1.1 https://github.com/postcss/postcss-url --depth=1 ./tmp": No such file or directory
Exception in thread "main" java.lang.NullPointerException
at Test.main(Test.java:18)当我使用"git -h“或"ls”时,它工作得很好。但是,这个命令/bin/bash -c "/usr/bin/git clone --branch 10.1.1 https://github.com/postcss/postcss-url --depth=1 ./tmp"在shell中有效,但在Java中失败。我该如何解决这个问题?
发布于 2020-12-23 16:09:00
您必须将-c作为单独的参数传递,并且不应在命令中添加文字双引号:
new String[]{ "bash", "-c", "git clone ..." }这是因为空格和引号是shell语法,而Runtime.exec不会调用它们来运行命令(这恰好是shell调用,但这是无关的)
https://stackoverflow.com/questions/65420764
复制相似问题