大数据学习之IO读取数据到hbase表中

一、将数据文件通过IO读入hbase表中

1.连接hbase的对象,调用getTable获取表的实例

2.创建一个ArraryList集合

3.用io读取文件数据,用while循环split进行分割成数组

3.1把每一行组成一个put对象以唯一的数为行键

3.2为行添加多列

3.3把每一行组成一个put对象添加到集合中

4.调用表的put方法将集合中的数据添加到表中;

5.关闭通道

示例代码:

/**
 * 连接hbase
 * */
@Before
public void clientHbase(){
    try {
        //获取hadoop相关配置
        Configuration conf = new Configuration();
        //获取zookeeper相关配置
        conf.set("hbase.zookeeper.quorum","master:2181,node1:2181,node2:2181");
        conn = HConnectionManager.createConnection(conf);
        //对DDL表进行操作,
        hBaseAdmin = new HBaseAdmin(conf);
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println("建立连接成功"+conn+",获取master成功"+hBaseAdmin);
}

/**读取数据*/
@Test
public void putAll() {

    try {
        //对表创建实例
        HTableInterface students = conn.getTable("s_demo1");


        //创建list集合
        ArrayList<Put> puts = new ArrayList<>();

        //io数据读取
        BufferedReader br = null;
        br = new BufferedReader(new FileReader("D:\\project_daima\\hadoop_bigdata\\hadoop-hbase\\data\\students.txt"));
        String line=null;
        while ((line=br.readLine())!=null){
            String[] split = line.split(",");
            String id = split[0];
            String name = split[1];
            String age = split[2];String gender = split[3];
            String clazz = split[4];

            //把每一行组成一个put对象,设定行键
            Put put = new Put(id.getBytes());

            //为一行添加多列
            put.add("info".getBytes(),"name".getBytes(),name.getBytes());
            put.add("info".getBytes(),"age".getBytes(),age.getBytes());
            put.add("info".getBytes(),"gender".getBytes(),gender.getBytes());
            put.add("info".getBytes(),"clazz".getBytes(),clazz.getBytes());

            //把每一行组成一个put对象添加到集合中
            puts.add(put);
        }

        //调用表的put方法将集合中的数据添加到表中
       students.put(puts);
        System.out.println("学生信息表添加完毕");

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

/**
 * 关闭通道
 * */
@After
public void closeTong(){
    if (conn!=null){
        try {
            conn.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    System.out.println("conn已关闭" );

    if (hBaseAdmin!=null){
        try {
            hBaseAdmin.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    System.out.println("master已关闭");

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值