mongodb上传数据 java语言版

来源:互联网 发布:战舰世界兴登堡数据 编辑:程序博客网 时间:2024/06/07 08:43

mongodb 可以用于构建文件存储系统。

package cache.cache;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.nio.ByteBuffer;import java.nio.channels.FileChannel;import java.util.ArrayList;import java.util.List;import java.util.concurrent.TimeoutException;import com.mongodb.MongoClient;import com.mongodb.MongoCredential;import com.mongodb.ServerAddress;import com.mongodb.client.MongoDatabase;import com.mongodb.client.gridfs.GridFSBucket;import com.mongodb.client.gridfs.GridFSBuckets;import com.mongodb.client.gridfs.GridFSUploadStream;public class App2 {    private static MongoClient mongoClient;    public static void main(String[] args) throws IOException, TimeoutException {        ServerAddress serverAddress = new ServerAddress("ip", 27017);        List<ServerAddress> addrs = new ArrayList<ServerAddress>();        addrs.add(serverAddress);        // MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码        MongoCredential credential = MongoCredential.createScramSha1Credential("zdc", "test", "12345678".toCharArray());        List<MongoCredential> credentials = new ArrayList<MongoCredential>();        credentials.add(credential);        mongoClient = new MongoClient(addrs, credentials);        // 连接到数据库        MongoDatabase mongoDatabase = mongoClient.getDatabase("test");        GridFSBucket gfsbk = GridFSBuckets.create(mongoDatabase);        GridFSUploadStream uploadStream = gfsbk.openUploadStream("xxx");//上传数据        uploadStream.write(toByteArray2("C://Users//thinkpad//Downloads//PuTTY_0.67.0.0.exe"));        uploadStream.flush();        uploadStream.close();    }    public static byte[] toByteArray2(String filename) throws IOException {        File f = new File(filename);        if (!f.exists()) {            throw new FileNotFoundException(filename);        }        FileChannel channel = null;        FileInputStream fs = null;        try {            fs = new FileInputStream(f);            channel = fs.getChannel();            ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size());            while ((channel.read(byteBuffer)) > 0) {                // do nothing                // System.out.println("reading");            }            return byteBuffer.array();        } catch (IOException e) {            e.printStackTrace();            throw e;        } finally {            try {                channel.close();            } catch (IOException e) {                e.printStackTrace();            }            try {                fs.close();            } catch (IOException e) {                e.printStackTrace();            }        }    }}
0 0
原创粉丝点击