2016-03-01 27 views
0

所以我尝试从java(jdk v1.8)备份mongodb(v3.2),到目前为止我想出了mongo java驱动不提供任何类的备份数据库。雁追逐最好的解决办法是 - 这样做,从Runtimemongodb-java-driver 3.2不能运行mongoexport

下面的代码

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 

但问题是,它不创建以.json文件。我错在哪里?感谢您的建议和解答!

+0

只是想知道如果timeAndDate字符串包含禁止的字符 – profesor79

+0

是的,空格不允许(或至少不工作) – Saleem

回答

1

我看到你犯了几个错误。但让我先发布为工作代码,然后我将解释你的代码有什么问题。

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(); 
} 

问题#1

的DateFormat DATEFORMAT =新的SimpleDateFormat( “YYYY-MM-DD HH-毫米-β”);

出于某种原因,mongoexport与日期格式字符串有问题。正如你所看到的,dd HH之间有空格。如果你保持这种格式。你会得到以下错误。

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

问题#2

文件文件=新的文件( “备份/” + timeAndDate); 在这里,你在你的路径FOOS有一个斜杠--- OUT /备份/”指向根文件夹,但它缺少当您创建持有的备份文件夹中。

+0

这是一个很好的答案,谢谢! –