从MongoDb读文件

代码示例

package test;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.bson.Document;
import org.bson.types.Binary;

import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;

public class MongoDBJDBC {

    public static void main(String args[]) {

        // 连接到Mongodb服务
        MongoClient mongoClient = new MongoClient("127.0.0.1", 27017);
        try {
            // 连接到数据库.如果库不存在则创建
            MongoDatabase db = mongoClient.getDatabase("ddj");
            // 选择表.如果表不存在则创建表
            MongoCollection collection = db
                    .getCollection("apfile");


            // 按条件查询遍历表
            MongoCursor cursor = collection.find().iterator();

            if (cursor.hasNext()) {
                //得到oracle中blob字段的对应字段(mongobd的binData二进制块)
                Binary binary = (Binary)cursor.next().get("FILE_CONT");
                //拿到字节数组
                byte[] filebyte = binary.getData();
                byte type = binary.getType();
                System.out.println(type);
                System.out.print(filebyte);
                //将文件的字节数组,写入硬盘
                writeFile("C:/Users/zhaoyf/Desktop/888.png",filebyte,"UTF-8");

            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭连接

            mongoClient.close();
        }
    }

    public static boolean writeFile(String filePath, byte[] bytes, String encoding) throws IOException {
        File file = new File(filePath);
        if (!file.getParentFile().exists()) {
            if (!file.getParentFile().mkdirs()) {
                return false;
            }
        }
        FileOutputStream fos = new FileOutputStream(file);
        byte[] bbuf = new byte[1024];
        InputStream bis = new ByteArrayInputStream(bytes);
        int hasRead = 0;
        //循环从输入流中取出数据
        while ((hasRead = bis.read(bbuf)) > 0) {
            fos.write(bbuf, 0, hasRead);
        }
        fos.close();
        bis.close();

        return true;
    }
}

你可能感兴趣的:(MongoDB,Java)