概述
Java API实现向Hive批量导入数据
原文地址:https://blog.csdn.net/kangkangwanwan/article/details/78915134
博主:盛装吾步
稍微修改了下,这文章是通过将数据存盘后,加载到HIVE.
模拟数据放到HDFS然后加载到HIVE,请大家记得添加HIVE JDBC依赖否则会报错。
加载前的数据表最好用外部表,否则会drop表的时候元数据会一起删除!
<dependency>
<groupId>org.apache.hive</groupId>
<artifactId>hive-jdbc</artifactId>
<version>1.1.0</version>
</dependency>
代码
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
public class Demo {
public static void main(String[] args) throws Exception {
List<List> argList = new ArrayList<List>();
List<String> arg = new ArrayList<String>();
arg.add("12345");
arg.add("m");
argList.add(arg);
arg = new ArrayList<String>();
arg.add("54321");
arg.add("f");
argList.add(arg);
// System.out.println(argList.toString());
String dst = "/test/kk.txt";
createFile(dst,argList);
// loadData2Hive(dst);
}
/**
* 将数据插入hdfs中,用于load到hive表中,默认分隔符是"|"
* @param dst
* @param contents
* @throws IOException
* @throws Exception
* @throws InterruptedException
*/
public static void createFile(String dst , List<List> argList) throws IOException, InterruptedException, Exception{
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(new URI("hdfs://hadoop:9000"),conf,"root");
Path dstPath = new Path(dst); //目标路径
//打开一个输出流
FSDataOutputStream outputStream = fs.create(dstPath);
StringBuffer sb = new StringBuffer();
for(List<String> arg:argList){
for(String value:arg){
sb.append(value).append("|");
}
sb.deleteCharAt(sb.length() - 1);//去掉最后一个分隔符
sb.append("n");
}
byte[] contents = sb.toString().getBytes();
outputStream.write(contents);
outputStream.flush();;
outputStream.close();
fs.close();
System.out.println("文件创建成功!");
}
/**
* 将HDFS文件load到hive表中
* @param dst
*/
public static void loadData2Hive(String dst) {
String JDBC_DRIVER = "org.apache.hive.jdbc.HiveDriver";
String CONNECTION_URL = "jdbc:hive2://hadoop:10000/default";
String username = "root";
String password = "root";
Connection con = null;
try {
Class.forName(JDBC_DRIVER);
con = (Connection) DriverManager.getConnection(CONNECTION_URL,username,password);
Statement stmt = con.createStatement();
String sql = " load data inpath '"+dst+"' into table test ";//test 为插入的表
stmt.execute(sql);
System.out.println("loadData到Hive表成功!");
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}finally {
// 关闭rs、ps和con
if(con != null){
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
最后
以上就是愉快鼠标为你收集整理的java 批量插入hive中转在HDFS的全部内容,希望文章能够帮你解决java 批量插入hive中转在HDFS所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复