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就中枪。

  • 相关阅读:
    我的python中级班学习之路(全程笔记第一模块) (第一章)语言基础
    Python_常用模块
    Python_装饰器、迭代器、生成器
    Python_函数
    Python_深浅拷贝
    Python_文件操作
    Python_三级目录
    Python_循环判断表达式
    Python_基础语法
    7段数码管绘制
  • 原文地址:https://www.cnblogs.com/longhua828/p/mongdb_java_no_gridfs_error_fix.html
Copyright © 2011-2022 走看看