java-MongoDB存入文件时奇怪的异常

#pre
     本来把打算 文件直接放到服务器上,不过好像直接把 文件塞进mongodb更好一些
就打算试一试,老样子百度关键字,看了一些博客之后(= =是不是应该先看官方API)
整理成一段了会报错的代码←_←
public static void test() throws IOException {
File fin=new File("D:/视听资源/音乐/rm/ruki.mp3");
MongoClient mc=new MongoClient();
DB db=new DB(mc,"test");
GridFS gridFS=new GridFS(db);
GridFSInputFile gridFSInputFile =gridFS.createFile(fin);
gridFSInputFile.save();
}

#报错
Exception in thread "main" com.mongodb.MongoException: couldn't save chunks
at com.mongodb.gridfs.GridFSInputFile.save(GridFSInputFile.java:180)
at com.mongodb.gridfs.GridFSInputFile.save(GridFSInputFile.java:160)
at com.listentome.DB.Operations.test.test(test.java:30)
at com.listentome.DB.Operations.test.main(test.java:21)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
Caused by: java.io.IOException:  Stream Closed
at java.io.FileInputStream.readBytes(Native Method)
at java.io.FileInputStream.read(FileInputStream.java:272)
at com.mongodb.gridfs.GridFSInputFile._readStream2Buffer(GridFSInputFile.java:307)
at com.mongodb.gridfs.GridFSInputFile.saveChunks(GridFSInputFile.java:228)
at com.mongodb.gridfs.GridFSInputFile.save(GridFSInputFile.java:178)
... 8 more
看错误日志发现是在调用save函数的时候 文件流关闭了
然后就着这个错误搜啊搜没找着符合这个情况的解释←_←

#然后为什么会发生Stream Closed此等奇怪的错误
     不小心发现了 gridFS.createFile 这个方法重载了好几个,然后就把上边那一行改成了
GridFSInputFile gridFSInputFile =gridFS.createFile(new FileInputStream(fin));
然后好了←_←,为什么会这样,传入File和传入InputStream应该一样吧

#点进源码看了看
public GridFSInputFile createFile(File file) throws IOException {
FileInputStream fileInputStream = new FileInputStream(file);

GridFSInputFile var3;
try {
var3 =
this.createFile(fileInputStream, file.getName(), true);
}
finally {
fileInputStream.close(); //←_←就是这里,它自己给关了所以save的时候报错了! }

return var3;
}
public GridFSInputFile createFile(InputStream in) {
return this.createFile(in, (String)null);
}

你可能感兴趣的:(MongoDB学习笔记)