创建一个maven项目,加入以下依赖
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.6.3</version>
</dependency>
创建一个TestMongo.java,内容如下:
import com.mongodb.DB;
import com.mongodb.Mongo;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSInputFile;
import org.bson.types.ObjectId;
import java.io.File;
public class MongoTest {
public static void main(String[] args) {
download("5e4be8c63930f446e42b8c65","C:/Users/zhangli/Desktop/1.png");
}
public static void download(String id,String filepath) {
try {
Mongo db = new Mongo("127.0.0.1", 27017);
DB mydb = db.getDB("tf");
GridFS myFS = new GridFS(mydb);
GridFSDBFile gridFSDBFile = myFS.findOne(new ObjectId(id));
gridFSDBFile.writeTo(filepath);
db.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void upload(String filepath) {
try {
Mongo db = new Mongo("127.0.0.1", 27017);
DB mydb = db.getDB("tf");
File f = new File(filepath);
GridFS myFS = new GridFS(mydb);
GridFSInputFile inputFile = myFS.createFile(f);
inputFile.save();
System.out.println(inputFile.getId());
db.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
测试
先执行upload方法,确保本地文件路径正确,上传完毕,记录打印的文件id,在通过该id,执行download方法。
以上就是java访问mongodb存取文件的过程。