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. VS2013中Django流水账笔记--配置环境

    一.开发环境 Win7 64位搭建开发环境.需要准备VS2013.Python34.PTVS2013. 1.http://pytools.codeplex.com/ 下载工具,下载之后进行安装即可,我 ...

  2. Apose 套打

    给web添加一个dll引用:Apose.Words 下载链接:http://yunpan.cn/cA7v6uceM6KVw  提取码 11df 在Global.asax里面的Application_S ...

  3. python(一)入门

    1.软件环境安装和配置 首先下载属于你的操作系统的对应的python安装包 2.傻瓜化下一步下一步 我直接勾选了配置python到path变量 然后完成 3.cmd命令行中测试一把 表示环境配置成功 ...

  4. Unity3D--学习太空射击游戏制作(四)

    步骤七:添加声音和特效(射击声音和爆炸效果) 01:在Project窗口单机右键,选择Import Package->Custome Package,然后到资源文件目录packages浏览uni ...

  5. shell中的重定向(2>&1)

    shell的输出可以分为标准输出和错误输出,2>&1中,2代表错误输出,1代表标准输出,&符号代表后面跟的是代号而不是文件. test.sh echo '我是标准输出' ls / ...

  6. Java基础知识学习

    1.什么是Java编程语言 Java是:一种编程语言.一种开发环境.一种应用环境.一种部署环境 2.Java编程语言的主要目标 (1)提供一种解释环境为:提高开发速度.代码可移植性.使用户能运行不止一 ...

  7. UNICODE编码表

    UNICODE简介 Unicode(统一码.万国码.单一码)是一种在计算机上使用的字符编码.Unicode 是为了解决传统的字符编码方案的局限而产生的,它为每种语言中的每个字符设定了统一并且唯一的二进 ...

  8. Unity之串口通信(基于三姿态传感器)

    原地址:http://www.cnblogs.com/alongu3d/archive/2013/05/02/3054962.html /******************************* ...

  9. Es索引优化

    https://www.elastic.co/guide/en/elasticsearch/guide/current/hardware.html https://www.elastic.co/gui ...

  10. jacob访问ocx控件方法和遇到的问题

    最近在进行摄像机的二次开发,摄像机厂商提供了使用C++开发的ocx控件:所以尝试使用jacob来进行访问. 操作步骤如下: 1, 从官网(http://sourceforge.net/projects ...