简体   繁体   中英

mongodb-java-driver 3.2 cannot mongoexport with runtime

so I try to backup mongodb(v3.2) from java(jdk v1.8) and so far I came up that mongo java driver doesn't provide any classes for backuping databases. After wild goose chase the best solution was - doing that from Runtime

Here's the code

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
Date date = new Date();
String timeAndDate = dateFormat.format(date);
File file = new File("backups/"+timeAndDate);
file.mkdirs();
Runtime.getRuntime().exec("mongoexport --db cookbook --collection foos --out /backups/"+ timeAndDate + "/foos.json;");
Runtime.getRuntime().exec("mongoexport --db cookbook --collection bars --out /backups/"+ timeAndDate + "/bars.json;"); // ignores perhaps

But the problem is that it doesn't create the .json files. Where am I wrong. Thank you for suggestions and answers!

I see you are making couple of mistakes. But let me first publish as working code and then I'll explain what's wrong with your code.

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
Date date = new Date();
String timeAndDate = dateFormat.format(date);

File file = new File("backups/"+timeAndDate);
file.mkdirs();

try {

    String command = "mongoexport --db cookbook --collection foo --out \"backups/"+ timeAndDate + "/foos.json\"";

    Process p = Runtime.getRuntime().exec(command);
    BufferedReader reader = new BufferedReader(new InputStreamReader(p.getErrorStream()));

    while(reader.ready())
    {
        System.out.println(reader.readLine());
    }

    System.in.read();

} catch (IOException e) {
    e.printStackTrace();
}

Problem #1

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");

For some reason, mongoexport has problem with date format string. As you can see there is space between dd HH. if you keep this format as it is. you'll get following error.

error parsing command line options: invalid argument for flag `-o, --out' (expected string): invalid syntax
try 'mongoexport --help' for more information

Problem #2

File file = new File("backups/"+timeAndDate); Here you have a forward slash in your path foos ---out /backups/" which points to root folder but it's missing in when you are creating folder which holds backup.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM