MongoDb 에서 파일 읽 기

4572 단어 MongoDBJava
코드 예제
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;
    }
}

좋은 웹페이지 즐겨찾기