zoukankan      html  css  js  c++  java
  • 【原】MongoDB Java版驱动调用GridFS.getFileList()报错:no gridfs!解决方法

    使用驱动版本:mongo-java-driver-2.9.3.jar

    问题原因:GridFS.getFileList()方法返回的GridFSDBFile对象的_fs字段未初始化

    解决方法:利用Java的反射机制手工赋值

    代码示例:

     1 Mongo mongo = new Mongo("localhost", 27017);
     2  
     3 DB db = mongo.getDB("demo");
     4  
     5 GridFS fs = new GridFS(db, theme);
     6  
     7 DBCursor fileList = fs.getFileList();
     8  
     9  
    10 Field _fs = GridFSFile.class.getDeclaredField("_fs"); // _fs字段所在的类为GridFSFile
    11 _fs.setAccessible(true);
    12 while (fileList.hasNext()) {
    13     GridFSDBFile next = (GridFSDBFile) fileList.next();
    14  
    15     // XXX bug 修复_fs字段为空的问题
    16     _fs.set(next, fs);
    17  
    18     // 保存文件操作
    19     next.writeTo(next.getId().toString());
    20  
    21     // 其他操作
    22     ...
    23  
    24 }
    25  
    26 fileList.close();
    27 mongo.close();

    另:

    GridFS的findOne(...),find(...)方法内都调用了GridFS._fix( Object o )方法对此问题进行了修正,所以一般这个问题也不容易被发现。没想到刚刚开始学习MongoDB就中枪。

  • 相关阅读:
    Spark RDD 创建(一)
    编译Spark-1.6.0源码
    Strom学习笔记一
    Hbase笔记——RowKey设计
    Hbase物理模型
    HDFS分布式文件系统设计思想
    Hbase 基本命令
    内部排序算法
    278. First Bad Version
    266. Palindrome Permutation
  • 原文地址:https://www.cnblogs.com/longhua828/p/mongdb_java_no_gridfs_error_fix.html
Copyright © 2011-2022 走看看