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文件的更多相关文章

  1. java Api 读取HDFS文件内容

    package dao; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.*; import java ...

  2. 使用JAVA API读取HDFS的文件数据出现乱码的解决方案

    使用JAVA api读取HDFS文件乱码踩坑 想写一个读取HFDS上的部分文件数据做预览的接口,根据网上的博客实现后,发现有时读取信息会出现乱码,例如读取一个csv时,字符串之间被逗号分割 英文字符串 ...

  3. JAVA API 实现hdfs文件操作

    java api 实现hdfs 文件操作会出现错误提示: Permission denied: user=hp, access=WRITE, inode="/":hdfs:supe ...

  4. Java API 读取HDFS的单文件

    HDFS上的单文件: -bash-3.2$ hadoop fs -ls /user/pms/ouyangyewei/data/input/combineorder/repeat_rec_categor ...

  5. Spark:java api读取hdfs目录下多个文件

    需求: 由于一个大文件,在spark中加载性能比较差.于是把一个大文件拆分为多个小文件后上传到hdfs,然而在spark2.2下如何加载某个目录下多个文件呢? public class SparkJo ...

  6. 使用java api操作HDFS文件

    实现的代码如下: import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import ...

  7. 记录一次读取hdfs文件时出现的问题java.net.ConnectException: Connection refused

    公司的hadoop集群是之前的同事搭建的,我(小白一个)在spark shell中读取hdfs上的文件时,执行以下指令 >>> word=sc.textFile("hdfs ...

  8. Spark读取HDFS文件,文件格式为GB2312,转换为UTF-8

    package iie.udps.example.operator.spark; import scala.Tuple2; import org.apache.hadoop.conf.Configur ...

  9. 使用Java API操作HDFS文件系统

    使用Junit封装HFDS import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.*; import org ...

随机推荐

  1. android xml产生和解析

    public static void writeToXml(Map<String, Object> map,Writer writer) throws Exception, Illegal ...

  2. TP框架多上传域上传图片

    问题: 学习使用TP框架做电商网站是,添加商品表单需要上传商品logo和商品图片pics,有两个上传域,第一个上传域是logo,只上传一张,第二个上传域是pics,上传多张图片.使用如下代码,总是报错 ...

  3. python的生成器

    1.生成器 >>> def func1(): ... yield 0 ... yield 1 ... >>> a=func1() >>> a.ne ...

  4. poj 1830 开关问题

    开关问题 题意:给n(0 < n < 29)开关的初始和最终状态(01表示),以及开关之间的关联关系(关联关系是单向的输入a b表示a->b),问有几种方式得到最终的状态.否则输出字 ...

  5. 关于ASE日志空间示数不正常的解决办法

        最近某系统的ASE数据库出现了异常,经过各种努力,终于把数据库正常又起起来了.但是经过检查,发现在查看剩余日志空间的时候(sp_helpsegment 'logsegment'),发现显示出来 ...

  6. Python之添加新元素

    现在,班里有3名同学: >>> L = ['Adam', 'Lisa', 'Bart'] 今天,班里转来一名新同学 Paul,如何把新同学添加到现有的 list 中呢? 第一个办法是 ...

  7. linux环境下验证码不显示的几种情况

    linux环境下验证码不显示的几种情况 gd库扩展没有安装. 查看phpinfo(),看看有没有安装gd库 yum安装gd库或者phpize安装 安装完成后记得重启php-fpm bom头的原因 在生 ...

  8. 更改nginx网站根目录

    默认网站根目录为/usr/local/nginx/html,要将它改成/homw/www vi /usr/local/nginx/conf/nginx.conf 将其中的           loca ...

  9. Oracle客户端PL_SQL的安装

    Oracle数据库的操作大多还是在客户端完成的,因此在众多的客户端软件中我选择了PL_SQL,一下谈谈PL_SQL的基本安装和操作,以及在操作中碰到的一些问题: 1. 首先下载PL_SQL客户端软件, ...

  10. Design Tutorial: Inverse the Problem

    Codeforces Round #270 D:http://codeforces.com/contest/472/problem/D 题意:给以一张图,用邻接矩阵表示,现在问你这张图能不能够是一棵树 ...