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

 

转载于:https://www.cnblogs.com/longhua828/p/mongdb_java_no_gridfs_error_fix.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值