【发布时间】:2017-01-26 10:15:12
【问题描述】:
我正在尝试编写一个可以从命令行执行vagrant 的Java 类:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.List;
public class Hello {
public static void deploy() {
String path = System.getProperty("user.home") + "/ansible/solr/";
try {
String command = "vagrant up";
ProcessBuilder builder = new ProcessBuilder(command);
System.out.println("------------------------------------------------");
System.out.println("Executing " + command + " in directory " + path);
System.out.println("Current path: " + Paths.get(".").toAbsolutePath().normalize().toString());
builder.directory(new File(path));
Process child = builder.start();
watch(child);
System.out.println("------------------------------------------------");
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
private static void watch(final Process process) {
new Thread() {
@Override
public void run() {
BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
try {
System.out.println("------------------------------------------------");
System.out.println("Executing Ansible");
while ((line = input.readLine()) != null) {
System.out.println(line);
}
System.out.println("------------------------------------------------");
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}.start();
}
public static void main(String[] args) {
deploy();
}
}
在我拥有的/ansible/solr 目录中:
-rw-r--r-- 1 ubuntu staff 2.1K Sep 17 08:36 README.md
-rw-r--r-- 1 ubuntu staff 840B Sep 17 08:36 Vagrantfile
drwxr-xr-x 4 ubuntu staff 136B Sep 17 08:36 provisioning/
-rw-r--r-- 1 ubuntu staff 80B Sep 17 08:36 requirements.yml
并且目录/home/ubuntu/ansible/solr 显然存在。
当我执行上面的程序时,我得到:
------------------------------------------------
Executing vagrant up in directory /home/ubuntu/ansible/solr
Current path: /home/ubuntu
Cannot run program "vagrant up" (in directory "/home/ubuntu/ansible/solr"): error=2, No such file or directory
为什么会出现这个错误?
【问题讨论】:
-
ProcessBuilder不是外壳!你需要new ProcessBuilder("vagrant", "up")
标签: java command-line solr process