一、将数据文件通过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已关闭"); }
、 |