2016-03-01 26 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

這是一個很好的答案,謝謝! –