zoukankan      html  css  js  c++  java
  • JAVA--将MongoDB数据写出到CSV

    package com.ReadMongodbToCsv;
    
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.net.UnknownHostException;
    import java.util.ArrayList;
    
    import com.mongodb.BasicDBObject;
    import com.mongodb.DB;
    import com.mongodb.DBCollection;
    import com.mongodb.DBCursor;
    import com.mongodb.Mongo;
    
    public class WriteCsv {
        private static Mongo mg;
        private static DB db;
        private static BufferedWriter bw ;
        public static void main(String args[]){
            initToMongoDB();
            try {
                bw = new BufferedWriter(new FileWriter(new File("F:/vv.csv")));
                DBCollection dd = db.getCollection("zq2");
                DBCursor dc = dd.find();
                int num = 0;
                while(dc.hasNext()){
                    num++;
                    BasicDBObject basi = (BasicDBObject)dc.next();
                    ArrayList<BasicDBObject> list = (ArrayList<BasicDBObject>)basi.get("l");
                    String ss = "";
                    StringBuffer sb = new StringBuffer();
                    sb.append(basi.get("z") + ",");
                    sb.append(basi.get("n") + ",");
                    for(BasicDBObject b : list){
                        sb.append(b.get("n") + ",");
                        sb.append(b.get("t") + ",");
                    }
                    sb = sb.deleteCharAt(sb.length() - 1);
                    bw.write(sb.toString() + "
    ");
                    if(num % 10000 == 0){
                        bw.flush();
                    }
                }
                System.out.println("写入完成");
            } catch (IOException e) {
                e.printStackTrace();
            }finally{
                if(bw != null){
                    try {
                        bw.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            
        }
        
        public static void initToMongoDB(){
            try {
                mg = new Mongo("localhost",27017);
                db = mg.getDB("admin");
                boolean auth = db.authenticate("root", "root".toCharArray());
                if(auth){
                    db = mg.getDB("test");
                }else{
                    System.err.println("mongodb链接失败");
                }
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
        }
    }
  • 相关阅读:
    image对象
    Frame/IFrame 对象
    Form 对象
    JavaScript 对象 实例
    button对象
    正则介绍以及多种使用方法
    js /jquery停止事件冒泡和阻止浏览器默认事件
    一些兼容性的知识
    面试题总结
    事件
  • 原文地址:https://www.cnblogs.com/zqzdong/p/4840894.html
Copyright © 2011-2022 走看看