通过java取mongodb数据_用java在客户端读取mongodb中的数据并发送至服务器

packagecom.cn.gao;import java.net.*;import java.io.*;import com.mongodb.*;/*** 客户端发送消息给服务器

*@authorhadoop

**/

public classClient {privateSocket client;private booleanconnected;//客户端构造函数

public Client(String host,intport){try{

client= newSocket(host,port);

System.out.println("连接服务器成功!");this.connected = true;

}catch(UnknownHostException e) {

System.out.println("无法解析主机名!");this.connected = false;

}catch(IOException e) {

System.out.println("输入输出错误!");this.connected = false;

closeSocket();

}

}//判断是否连接

public booleanisConnected(){returnconnected;

}//设置连接状态

public void setConnected(booleanconnected){this.connected =connected;

}/*** 发送数据到端口

*@paramdbname mongodb数据库名字

*@paramcollectionName 该数据库中要发送数据的collection名*/

public voidsendFile(String dbname,String collectionName){

DataOutputStream dos= null;

DataInputStream dis= null;if(client==null) return;//从mongodb数据库中读取数据

Mongo connection = new Mongo("localhost:27017");

DB db=connection.getDB(dbname);

DBCollection input=db.getCollection(collectionName);/*BasicDBObject condition=new BasicDBObject();//条件

BasicDBObject key=new BasicDBObject("vtext",2);//指定需要显示列

DBCursor cur = input.find(condition,key);*/DBCursor cur=input.find();try{while(cur.hasNext()){

DBObject document=cur.next();

dis= new DataInputStream(newByteArrayInputStream(document.toString().getBytes()));

dos= newDataOutputStream(client.getOutputStream());int bufferSize = 10240;byte[] buf = new byte[bufferSize];int num =0;while((num=dis.read(buf))!=-1){

System.out.println(newString(buf));

dos.write(buf,0, num);

}

dos.flush();

}

System.out.println("传输成功!");

}catch(IOException e) {

e.printStackTrace();//System.out.println("输入输出错误!");

closeSocket();

}finally{try{if(dis!=null) dis.close();if(dos!=null) dos.close();

}catch(IOException e) {

e.printStackTrace();//System.out.println("输入输出错误!");

}

}

}//关闭客户端

public voidcloseSocket(){if(client!=null){try{

client.close();

}catch(IOException e) {

e.printStackTrace();

}

}

}/***@paramargs

* 参数格式如下

* hostname dbname collectionName*/

public static voidmain(String[] args){//默认端口为8888

if(args.length!=3){

System.out.println("参数格式不对!");return;

}

String hostName= args[0];int port = 8888;

Client client= null;

client= newClient(hostName,port);

String dbname= args[1];

String collectionName= args[2];if(client.isConnected()){

client.sendFile(dbname, collectionName);

client.closeSocket();

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值