2016-01-13 62 views
1

我想在mongoDB中存儲一個文件並從中檢索它來處理它。 我已經使用了GridFS的存儲它使用Java&GridFs在MongoDB中存儲和重試文件

Mongo mongo = new Mongo("localhost", 27017); 
    DB db = mongo.getDB("HelloWorldDB"); 
    DBCollection collection = db.getCollection("Uploaded_Exclusion_files"); 
    GridFS gridfs = new GridFS(db, "downloads"); 
    GridFSInputFile gfsFile = gridfs.createFile(new File(fileName)); 
    gfsFile.setFilename("filename"); 
    gfsFile.save(); 

    BasicDBObject info = new BasicDBObject(); 
    info.put("name", "MongoDB"); 
    info.put("fileName", "filename"); 
    info.put("rawName", "fromJSON.csv"); 
    info.put("rawPath", "d:/fromJSON.csv"); 

    // 
    // Let's store our document to MongoDB 
    // 
    collection.insert(info, WriteConcern.SAFE); 


    DBCursor cursor= collection.find(info); 
    while(cursor.hasNext()){ 
     System.out.println("Result "+cursor.next()); 
    } 
     System.out.println("Done");  

,但在檢索文件的時間,我不我知道該怎麼做它作爲一個文件,並對其進行處理。

  GridFSDBFile gfsFileOut = (GridFSDBFile) gridfs.findOne("filename"); 
      System.out.println(gfsFileOut.getInputStream()); 
      //##### WHAT TO DO TO GET THE FILE 

    BufferedReader br = null; 
    try { 
     String sCurrentLine; 
     br = new BufferedReader(new FileReader(<#####I WANT TO PASS THE FILE TO PROCESS IT######>)); 

     // ...   
    } catch (IOException e) { 
     e.printStackTrace(); 
    } finally { 
     try { 
      if (br != null) 
       br.close(); 
     } catch (IOException ex) { 
      ex.printStackTrace(); 
     } 
    } 

我想刪除服務器中的文件創建部分,只想存儲在mongodb中並檢索它來處理它。

回答

1

我得到了答案使用GridFS的

GridFSDBFile gfsFileOut = (GridFSDBFile) gridfs.findOne(rawName); 
    System.out.println(gfsFileOut.getInputStream()); 
    InputStream is = gfsFileOut.getInputStream(); 

    // Reading the excel file 
    List<String> list = null; 
    BufferedReader br = null; 
    try { 
     String sCurrentLine; 
     br = new BufferedReader(new InputStreamReader(is, "UTF-8")); 
獲取從MongoDB的文件
相關問題