ProcessBuilder和RunTime.exec未在代码中运行我

时间:2018-12-24 05:37:10

标签: java processbuilder runtime.exec

我正在用Java为mongodb服务器编写一个应用程序,我需要:

1-启动我的Mongo DB服务器(在终端中是:“ mongod”)

2-访问Mongo并删除一个集合(在终端中执行:“ mongo”,“ use my_db”和“ db.user_coll.drop()”)

3-导入新集合(在终端中:“ mongoimport --db my_db--集合user_coll-文件user_coll”

我可以在终端中进行所有操作,但是当我尝试使用ProcessBuilder或getRunTime.exec()从Java运行时,不起作用:(

这是我的代码:

String DBPath ="";

if(args.length<=3) {
 System.out.println("Localizando collection em " + System.getProperty("user.home") + "/Desktop/");
 DBPath = System.getProperty("user.home") + "/Desktop/";
}
else { 
 String LastChar = 
 Character.toString(args[3].charAt(args[3].length()-1));
 if (LastChar == "/") {
  System.out.println("Localizando collection em " + args[3]);
  DBPath = args[3];
 }
 else{
  System.out.println("Localizando collection em " + args[3] + "/");
  DBPath = args[3]+ "/";
 }
}

File f = new File(DBPath + "user_coll");
if(f.isFile()) {
 System.out.println("Collection localizada, iniciando servidor MongoDB e derrubando a collection atual...");
 ProcessBuilder proc = new ProcessBuilder(new String[] {"/bin/bash", "-c", "mongod"});
 proc.start().waitFor();
 String echo = "cd "+ System.getProperty("user.dir")+ " && mongo < mongodbscript.js";
 Process proc2 = new ProcessBuilder(new String[] {"bash","-c", echo}).start();
 System.out.println("Importando nova collection...");
 Process proc3 = new ProcessBuilder(new String[] {"bash", "-c", "cd " + DBPath + " && mongoimport --db my_db --collection user_coll --file user_coll"}).start();
 System.out.println("Collection importada...");
}
else {
 System.out.println("Nova collection não localizada, iniciando servidor MongoDB com a collection existente");
 Process proc = new ProcessBuilder(new String[] {"bash", "-c", "mongod"}).start();
}

1 个答案:

答案 0 :(得分:0)

我一直在MacOS中处理此问题,并且找到了解决方法。

我将mongoimport命令的完整路径添加到exec命令:

Runtime r  = Runtime.getRuntime();

Process p = r.exec(path + command);

其中path =“ / Users /'myname'/ Documents / mongoInstallation / bin” 和comand =“ mongoimport”