用java api读取HDFS文件
import java.io.IOException;
import java.io.InputStream;
import java.security.PrivilegedExceptionAction;
import java.text.SimpleDateFormat;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap; import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FsStatus;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.security.UserGroupInformation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import bean.TableStatistic; @Controller
@RequestMapping("/dfview")
public class DataFrameViewController extends BaseController { private ConcurrentMap<String, UserGroupInformation> cache = new ConcurrentHashMap<String, UserGroupInformation>();
private ConcurrentMap<String, FileSystem> fileSystemCache = new ConcurrentHashMap<String, FileSystem>();
private Configuration hadoopConf = new Configuration();
private static final String HDFS_JSON_NAME = "jsonObj"; @RequestMapping(value = "/getDFviewOfColumn", method = { RequestMethod.GET })
@ResponseBody
public TableStatistic getDFviewOfTable(String tableName)
throws Exception {
String user = "bi";
String dirpath = "/user/cbt/datax/temp_transfer/zzzdes";
Path homePath = new Path(dirpath);
FileSystem fs = this.createFileSystem(user);
FileStatus[] stats = fs.listStatus(homePath);
StringBuffer txtContent = new StringBuffer();
for (int i = 0; i < stats.length; ++i) {
if (stats[i].isFile()) {
FileStatus file = stats[i];
if( HDFS_JSON_NAME.equalsIgnoreCase(file.getPath().getName())){
InputStream in = fs.open(file.getPath());
byte[] b = new byte[1];
while (in.read(b) != -1)
{
// 字符串拼接
txtContent.append(new String(b));
}
in.close();
break;
}
}
}
TableStatistic ts = JSON.parseObject(txtContent.toString(), TableStatistic.class);
return ts;
} public static void main(String[] args) throws Exception {
DataFrameViewController aaa = new DataFrameViewController();
FileSystem fs = aaa.createFileSystem("bi");
Path homePath = new Path("/user/cbt/datax/temp_transfer/zzzdes");
System.out.println("***********************************");
FileStatus[] stats = fs.listStatus(homePath);
for (int i = 0; i < stats.length; ++i) {
if (stats[i].isFile()) {
FileStatus file = stats[i];
StringBuffer txtContent = new StringBuffer();
if( "jsonObj".equalsIgnoreCase(file.getPath().getName())){
InputStream in = fs.open(file.getPath());
byte[] b = new byte[1];
while (in.read(b) != -1)
{
// 字符串拼接
txtContent.append(new String(b));
}
// IOUtils.copyBytes(fs.open(file.getPath()), System.out, 4096,false);
in.close();
// fs.close();
}
System.out.print(txtContent.toString());
System.out
.println("************************************************");
JSONObject jb = JSON.parseObject(txtContent.toString());
System.out.println("********!!!!! : " + jb.get("colUnique"));
TableStatistic ts = JSON.parseObject(txtContent.toString(), TableStatistic.class);
System.out.println("********!!!!! : " + ts.getColUnique().toString()); } else if (stats[i].isDirectory()) {
System.out.println(stats[i].getPath().toString());
} else if (stats[i].isSymlink()) {
System.out.println("&&&&&&&&" + stats[i].getPath().toString());
} }
FsStatus fsStatus = fs.getStatus(homePath);
} public FileSystem createFileSystem(String user) throws Exception {
final Configuration conf = loadHadoopConf();
conf.set("hadoop.job.ugi", user);
// conf.set("HADOOP_USER_NAME", user);
if (fileSystemCache.get(user) != null) {
return fileSystemCache.get(user);
}
UserGroupInformation ugi = getProxyUser(user);
FileSystem fs = ugi.doAs(new PrivilegedExceptionAction<FileSystem>() {
public FileSystem run() throws Exception {
return FileSystem.get(conf);
}
});
fileSystemCache.put(user, fs);
return fs;
} public static final ThreadLocal<SimpleDateFormat> appDateFormat = new ThreadLocal<SimpleDateFormat>() {
@Override
public SimpleDateFormat initialValue() {
SimpleDateFormat dateformat = new java.text.SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
return dateformat;
}
}; private static final String[] HADOOP_CONF_FILES = { "core-site.xml",
"hdfs-site.xml" }; private Configuration loadHadoopConf() {
if (hadoopConf != null) {
return hadoopConf;
}
Configuration conf = new Configuration();
for (String fileName : HADOOP_CONF_FILES) {
try {
InputStream inputStream = DataFrameViewController.class
.getClassLoader().getResourceAsStream(fileName);
conf.addResource(inputStream);
} catch (Exception ex) {
}
}
return conf;
} public void destroy() {
for (UserGroupInformation ugi : cache.values()) {
try {
FileSystem.closeAllForUGI(ugi);
} catch (IOException ioe) {
// Logger.error("Exception occurred while closing filesystems for "
// + ugi.getUserName(), ioe);
}
}
cache.clear();
} private UserGroupInformation getProxyUser(String user) throws IOException {
cache.putIfAbsent(user, UserGroupInformation.createRemoteUser(user));
return cache.get(user);
}
}
用java api读取HDFS文件的更多相关文章
- java Api 读取HDFS文件内容
package dao; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.*; import java ...
- 使用JAVA API读取HDFS的文件数据出现乱码的解决方案
使用JAVA api读取HDFS文件乱码踩坑 想写一个读取HFDS上的部分文件数据做预览的接口,根据网上的博客实现后,发现有时读取信息会出现乱码,例如读取一个csv时,字符串之间被逗号分割 英文字符串 ...
- JAVA API 实现hdfs文件操作
java api 实现hdfs 文件操作会出现错误提示: Permission denied: user=hp, access=WRITE, inode="/":hdfs:supe ...
- Java API 读取HDFS的单文件
HDFS上的单文件: -bash-3.2$ hadoop fs -ls /user/pms/ouyangyewei/data/input/combineorder/repeat_rec_categor ...
- Spark:java api读取hdfs目录下多个文件
需求: 由于一个大文件,在spark中加载性能比较差.于是把一个大文件拆分为多个小文件后上传到hdfs,然而在spark2.2下如何加载某个目录下多个文件呢? public class SparkJo ...
- 使用java api操作HDFS文件
实现的代码如下: import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import ...
- 记录一次读取hdfs文件时出现的问题java.net.ConnectException: Connection refused
公司的hadoop集群是之前的同事搭建的,我(小白一个)在spark shell中读取hdfs上的文件时,执行以下指令 >>> word=sc.textFile("hdfs ...
- Spark读取HDFS文件,文件格式为GB2312,转换为UTF-8
package iie.udps.example.operator.spark; import scala.Tuple2; import org.apache.hadoop.conf.Configur ...
- 使用Java API操作HDFS文件系统
使用Junit封装HFDS import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.*; import org ...
随机推荐
- Apose 套打
给web添加一个dll引用:Apose.Words 下载链接:http://yunpan.cn/cA7v6uceM6KVw 提取码 11df 在Global.asax里面的Application_S ...
- PHP 生成随机浮点数
<?php /** * @desc 获取随机浮点数(支持最大最小值参数互换) * @date 2014-11-07 17:04:21 * * @param int|\最小浮点数 $min 最小浮 ...
- 笨方法学python 33课
今天Eiffel看到了第33章,任务是把一个while循环改成一个函数. 我在把while循环改成函数上很顺利,但是不知道怎么写python的主函数,在参数的调用上也出现了问题. 通过查资料,发现py ...
- jenkins 重新设置 管理员密码
由于服务器瘫痪,修好之后经常不上,就把jenkins的管理密码忘掉了. 查阅了网上所有方案之后发现没有一个 能正确修改密码的,特此列出下列网上的方法 第一.设成无需密码验证的(网上有教程,不过并不能修 ...
- 聊天工具实现winform端实现
最近在找能够实现客户端点对点聊天的技术,通过github我发现了一个项目,它能够支持webscoket通讯,服务端是由c#socket完成. 我要的是winform端的通信,所以在他的基础上,增加了桌 ...
- 【JPA】两种不同的实现jpa的配置方法
两种不同的实现jpa的配置方法 第一种: com.mchange.v2.c3p0.ComboPooledDataSource datasource.connection.driver_class=co ...
- java枚举类型enum的使用
2015-10-24 java达人 Java 中 的枚举类型采用关键字enum 来定义,从jdk1.5才有的新类型,所有的枚举类型都是继承自Enum 类型.要了解枚举类型,建议大家先打开jdk 中的E ...
- cf Round 601
A.The Two Routes(BFS) 给出n个城镇,有m条铁路,铁路的补图是公路,汽车和火车同时从1出发,通过每条路的时间为1,不能同时到达除了1和n的其它点,问他们到达n点最少要用多长时间. ...
- linux nginx安装
操作系统centOS7安装nginx: 1.如果centOS7中未安装编译器,先安装gcc编译模块 yum install gcc gcc-c++ ncurses-devel perl 2.安装ngi ...
- sqlserver 2008express版本启用混合登陆和sa
本机环境:win10 64位 vs2010及其自带的数据库 sqlserver2008 express版本 用命令行登陆数据库: osql -E -Slocalhost\sqlexpress 登陆成 ...