2014-02-14 144 views
0

在Mongodb中,我有一個包含json文檔的測試集合。我能夠檢索JSON並將其記錄到我的IDE控制檯。現在我想將這個json存儲到我的本地文件系統中的文件(即test.json)中。我試圖創建這樣的代碼,但它不工作。第4行有一些問題,因爲文件無法寫入光標。將json寫入本地文件系統

如何從mongodb獲取對象到文件系統,是否有任何示例代碼與我共享。

DBCursor cursor = collection.find(); 

FileWriter file = new FileWriter("D:\\test1.json"); 
while(cursor.hasNext()) { 
    file.write(cursor.toJSONString(); // this is line 4 
} 
file.close(); 

System.out.println("JSON created successfully"); 
+0

你文件收盤前沖洗.... file.flush(); \t \t file.close() – Naren

回答

0

嘗試像這樣

import java.io.File; 
import java.io.FileWriter; 
import java.net.UnknownHostException; 

import com.mongodb.DB; 
import com.mongodb.DBCollection; 
import com.mongodb.DBCursor; 
import com.mongodb.DBObject; 
import com.mongodb.Mongo; 
import com.mongodb.MongoException; 
import com.mongodb.util.JSON; 



public class App { 
    public static void main(String[] args) throws Exception{ 

     try { 

      Mongo mongo = new Mongo("localhost", 27017); 
      DB db = mongo.getDB("test"); 
      DBCollection collection = db.getCollection("dummyColl"); 

      // convert JSON to DBObject directly 
      DBObject dbObject = (DBObject) JSON 
        .parse("{'name':'mkyong', 'age':30}"); 

      collection.insert(dbObject); 

      DBCursor cursorDoc = collection.find(); 
      while (cursorDoc.hasNext()) { 
       System.out.println(cursorDoc.next()); 
      } 

      String st=JSON.serialize(cursorDoc); 
      File file=new File("test.json"); 
      FileWriter fileWriter=new FileWriter(file); 
      fileWriter.write(st); 
      fileWriter.close(); 

      System.out.println("Done"); 

     } catch (UnknownHostException e) { 
      e.printStackTrace(); 
     } catch (MongoException e) { 
      e.printStackTrace(); 
     } 
    } 
} 
+0

This worked for me ..謝謝你Naren – Ilango

+0

歡迎@Ilango – Naren

0

這是失蹤(newwrite前):

file.open(); 
相關問題