I'm coding one application for my mongodb server in java, and I need to:
1 - Start my Mongo DB server (in terminal it is: "mongod")
2 - Access the Mongo and drop one collection (executing in terminal: "mongo", "use my_db" and "db.user_coll.drop()")
3 - Import the new collection (in terminal: "mongoimport --db my_db--collection user_coll --file user_coll"
I can make all this in terminal, but when i tried to run from Java, using ProcessBuilder or getRunTime.exec(), don't work :(
This is my code:
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();
}
I have been working with this problem in MacOS and I found a workaround.
I add the complete path of the mongoimport command to the exec command:
Runtime r = Runtime.getRuntime();
Process p = r.exec(path + command);
where path = "/Users/'myname'/Documents/mongoInstallation/bin" and comand = "mongoimport"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.