hadoop: hdfs API示例
利用hdfs的api,可以实现向hdfs的文件、目录读写,利用这一套API可以设计一个简易的山寨版云盘,见下图:

为了方便操作,将常用的文件读写操作封装了一个工具类:
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.io.IOUtils; import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream; /**
* HDFS工具类
* Author: 菩提树下的杨过(http://yjmyzz.cnblogs.com)
* Since: 2015-05-21
*/
public class HDFSUtil { private HDFSUtil() { } /**
* 判断路径是否存在
*
* @param conf
* @param path
* @return
* @throws IOException
*/
public static boolean exits(Configuration conf, String path) throws IOException {
FileSystem fs = FileSystem.get(conf);
return fs.exists(new Path(path));
} /**
* 创建文件
*
* @param conf
* @param filePath
* @param contents
* @throws IOException
*/
public static void createFile(Configuration conf, String filePath, byte[] contents) throws IOException {
FileSystem fs = FileSystem.get(conf);
Path path = new Path(filePath);
FSDataOutputStream outputStream = fs.create(path);
outputStream.write(contents);
outputStream.close();
fs.close();
} /**
* 创建文件
*
* @param conf
* @param filePath
* @param fileContent
* @throws IOException
*/
public static void createFile(Configuration conf, String filePath, String fileContent) throws IOException {
createFile(conf, filePath, fileContent.getBytes());
} /**
* @param conf
* @param localFilePath
* @param remoteFilePath
* @throws IOException
*/
public static void copyFromLocalFile(Configuration conf, String localFilePath, String remoteFilePath) throws IOException {
FileSystem fs = FileSystem.get(conf);
Path localPath = new Path(localFilePath);
Path remotePath = new Path(remoteFilePath);
fs.copyFromLocalFile(true, true, localPath, remotePath);
fs.close();
} /**
* 删除目录或文件
*
* @param conf
* @param remoteFilePath
* @param recursive
* @return
* @throws IOException
*/
public static boolean deleteFile(Configuration conf, String remoteFilePath, boolean recursive) throws IOException {
FileSystem fs = FileSystem.get(conf);
boolean result = fs.delete(new Path(remoteFilePath), recursive);
fs.close();
return result;
} /**
* 删除目录或文件(如果有子目录,则级联删除)
*
* @param conf
* @param remoteFilePath
* @return
* @throws IOException
*/
public static boolean deleteFile(Configuration conf, String remoteFilePath) throws IOException {
return deleteFile(conf, remoteFilePath, true);
} /**
* 文件重命名
*
* @param conf
* @param oldFileName
* @param newFileName
* @return
* @throws IOException
*/
public static boolean renameFile(Configuration conf, String oldFileName, String newFileName) throws IOException {
FileSystem fs = FileSystem.get(conf);
Path oldPath = new Path(oldFileName);
Path newPath = new Path(newFileName);
boolean result = fs.rename(oldPath, newPath);
fs.close();
return result;
} /**
* 创建目录
*
* @param conf
* @param dirName
* @return
* @throws IOException
*/
public static boolean createDirectory(Configuration conf, String dirName) throws IOException {
FileSystem fs = FileSystem.get(conf);
Path dir = new Path(dirName);
boolean result = fs.mkdirs(dir);
fs.close();
return result;
} /**
* 列出指定路径下的所有文件(不包含目录)
*
* @param conf
* @param basePath
* @param recursive
*/
public static RemoteIterator<LocatedFileStatus> listFiles(FileSystem fs, String basePath, boolean recursive) throws IOException { RemoteIterator<LocatedFileStatus> fileStatusRemoteIterator = fs.listFiles(new Path(basePath), recursive); return fileStatusRemoteIterator;
} /**
* 列出指定路径下的文件(非递归)
*
* @param conf
* @param basePath
* @return
* @throws IOException
*/
public static RemoteIterator<LocatedFileStatus> listFiles(Configuration conf, String basePath) throws IOException {
FileSystem fs = FileSystem.get(conf);
RemoteIterator<LocatedFileStatus> remoteIterator = fs.listFiles(new Path(basePath), false);
fs.close();
return remoteIterator;
} /**
* 列出指定目录下的文件\子目录信息(非递归)
*
* @param conf
* @param dirPath
* @return
* @throws IOException
*/
public static FileStatus[] listStatus(Configuration conf, String dirPath) throws IOException {
FileSystem fs = FileSystem.get(conf);
FileStatus[] fileStatuses = fs.listStatus(new Path(dirPath));
fs.close();
return fileStatuses;
} /**
* 读取文件内容
*
* @param conf
* @param filePath
* @return
* @throws IOException
*/
public static String readFile(Configuration conf, String filePath) throws IOException {
String fileContent = null;
FileSystem fs = FileSystem.get(conf);
Path path = new Path(filePath);
InputStream inputStream = null;
ByteArrayOutputStream outputStream = null;
try {
inputStream = fs.open(path);
outputStream = new ByteArrayOutputStream(inputStream.available());
IOUtils.copyBytes(inputStream, outputStream, conf);
fileContent = outputStream.toString();
} finally {
IOUtils.closeStream(inputStream);
IOUtils.closeStream(outputStream);
fs.close();
}
return fileContent;
}
}
简单的测试了一下:
@Test
public void test() throws IOException {
Configuration conf = new Configuration();
String newDir = "/test";
//01.检测路径是否存在 测试
if (HDFSUtil.exits(conf, newDir)) {
System.out.println(newDir + " 已存在!");
} else {
//02.创建目录测试
boolean result = HDFSUtil.createDirectory(conf, newDir);
if (result) {
System.out.println(newDir + " 创建成功!");
} else {
System.out.println(newDir + " 创建失败!");
}
}
String fileContent = "Hi,hadoop. I love you";
String newFileName = newDir + "/myfile.txt"; //03.创建文件测试
HDFSUtil.createFile(conf, newFileName, fileContent);
System.out.println(newFileName + " 创建成功"); //04.读取文件内容 测试
System.out.println(newFileName + " 的内容为:\n" + HDFSUtil.readFile(conf, newFileName)); //05. 测试获取所有目录信息
FileStatus[] dirs = HDFSUtil.listStatus(conf, "/");
System.out.println("--根目录下的所有子目录---");
for (FileStatus s : dirs) {
System.out.println(s);
} //06. 测试获取所有文件
FileSystem fs = FileSystem.get(conf);
RemoteIterator<LocatedFileStatus> files = HDFSUtil.listFiles(fs, "/", true);
System.out.println("--根目录下的所有文件---");
while (files.hasNext()) {
System.out.println(files.next());
}
fs.close(); //删除文件测试
boolean isDeleted = HDFSUtil.deleteFile(conf, newDir);
System.out.println(newDir + " 已被删除"); }
注:测试时,不要忘记了在resources目录下放置core-site.xml文件,不然IDE环境下,代码不知道去连哪里的HDFS
输出结果:
/test 已存在!
/test/myfile.txt 创建成功
/test/myfile.txt 的内容为:
Hi,hadoop. I love you
--根目录下的所有子目录---
FileStatus{path=hdfs://172.28.20.102:9000/jimmy; isDirectory=true; modification_time=1432176691550; access_time=0; owner=hadoop; group=supergroup; permission=rwxrwxrwx; isSymlink=false}
FileStatus{path=hdfs://172.28.20.102:9000/test; isDirectory=true; modification_time=1432181331362; access_time=0; owner=jimmy; group=supergroup; permission=rwxr-xr-x; isSymlink=false}
FileStatus{path=hdfs://172.28.20.102:9000/user; isDirectory=true; modification_time=1431931797244; access_time=0; owner=hadoop; group=supergroup; permission=rwxr-xr-x; isSymlink=false}
--根目录下的所有文件---
LocatedFileStatus{path=hdfs://172.28.20.102:9000/jimmy/input/README.txt; isDirectory=false; length=1366; replication=1; blocksize=134217728; modification_time=1431922483851; access_time=1432174134018; owner=hadoop; group=supergroup; permission=rw-r--r--; isSymlink=false}
LocatedFileStatus{path=hdfs://172.28.20.102:9000/jimmy/output/_SUCCESS; isDirectory=false; length=0; replication=3; blocksize=134217728; modification_time=1432176692454; access_time=1432176692448; owner=jimmy; group=supergroup; permission=rw-r--r--; isSymlink=false}
LocatedFileStatus{path=hdfs://172.28.20.102:9000/jimmy/output/part-r-00000; isDirectory=false; length=1306; replication=3; blocksize=134217728; modification_time=1432176692338; access_time=1432176692182; owner=jimmy; group=supergroup; permission=rw-r--r--; isSymlink=false}
LocatedFileStatus{path=hdfs://172.28.20.102:9000/test/myfile.txt; isDirectory=false; length=21; replication=3; blocksize=134217728; modification_time=1432181331601; access_time=1432181331362; owner=jimmy; group=supergroup; permission=rw-r--r--; isSymlink=false}
/test 已被删除
用spring-mvc结合hdfs api仿造hadoop的文件浏览管理界面,做了一个山寨版:(只完成了文件列表功能)

源代码托管在taobao开源平台上了,有需要的可以参考下:
http://code.taobao.org/p/hdfs-web-client/src/trunk/
hadoop: hdfs API示例的更多相关文章
- hadoop的API对HDFS上的文件访问
这篇文章主要介绍了使用hadoop的API对HDFS上的文件访问,其中包括上传文件到HDFS上.从HDFS上下载文件和删除HDFS上的文件,需要的朋友可以参考下hdfs文件操作操作示例,包括上传文件到 ...
- Hadoop学习之路(十)HDFS API的使用
HDFS API的高级编程 HDFS的API就两个:FileSystem 和Configuration 1.文件的上传和下载 package com.ghgj.hdfs.api; import org ...
- Hadoop 之 HDFS API操作
1. 文件上传 @Slf4j public class HDFSClient { @Test public void testCopyFromLocalFile() throws Exception{ ...
- Python API 操作Hadoop hdfs详解
1:安装 由于是windows环境(linux其实也一样),只要有pip或者setup_install安装起来都是很方便的 >pip install hdfs 2:Client——创建集群连接 ...
- Hadoop HDFS编程 API入门系列之HDFS_HA(五)
不多说,直接上代码. 代码 package zhouls.bigdata.myWholeHadoop.HDFS.hdfs3; import java.io.FileInputStream;import ...
- Hadoop HDFS编程 API入门系列之简单综合版本1(四)
不多说,直接上代码. 代码 package zhouls.bigdata.myWholeHadoop.HDFS.hdfs4; import java.io.IOException; import ja ...
- Hadoop 学习笔记(二) HDFS API
4.删除HDFS上的文件 package proj; import java.io.IOException; import org.apache.hadoop.conf.Configuration; ...
- hadoop学习笔记(七):Java HDFS API
一.使用HDFS FileSystem详解 HDFS依赖的第三方包: hadoop 1.x版本: commons-configuration-1.6.jar commons-lang-2.4.jar ...
- Python3调用Hadoop的API
前言: 上一篇文章 我学习使用pandas进行简单的数据分析,但是各位...... Pandas处理.分析不了TB级别数据的大数据,于是再看看Hadoop. 另附上人心不足蛇吞象 对故事一的感悟: ...
随机推荐
- Sql Server之旅——第九站 看公司这些DBA们设计的这些复合索引
这一篇再说下索引的最后一个主题,索引覆盖,当然学习比较好的捷径是看看那些大师们设计的索引,看从中能提取些什么营养的东西,下面我们看 看数据库中一个核心的Orders表. 一:查看表的架构 <1& ...
- Java并发工具类Semaphore应用实例
package com.thread.test.thread; import java.util.Random; import java.util.concurrent.*; /** * Semaph ...
- Thrift 跨服务开发框架
Thrift概述 Thrift是一个软件框架,用来进行可扩展且跨语言的服务的开发.它结合了功能强大的软件堆栈和代码生成引擎,以构建在 C++, Java, Python, PHP,Ruby, Erla ...
- HTML5游戏开发引擎,初识CreateJS
CreateJS为CreateJS库,可以说是一款为HTML5游戏开发的引擎.打造 HTML5 游戏,构建新游戏,提供构建最新 HTML5 的技术.你可以通过这个网站学习如何构建跨平台和跨终端游戏.这 ...
- Windows 保存BMP图片
在Windows下保存BMP图片还是挺方便的,直接上代码,拷贝就能用 void savebmp(uchar * pdata, char * bmp_file, int width, int heigh ...
- Makefile隐含规则
两个隐含规则; 将所有的name.o的依赖自动推导为name.c并使用规则$(CC) -c $(FLAGS) $(CPPFLAGS)得到目标.这个规则中只有-c是隐含规则中有的,后面两个变量是留给用户 ...
- 虚拟机centos6.5 --安装jdk
1.首先卸载默认安装的openjdk,如下 rpm -qa | grep java #查看当前是否已经安装了跟java有关的包 yum -y remove java #卸载 rpm -qa |grep ...
- CPU和GPU性能对比
计算20000次10000点的fft,分别使用CPU和GPU,得 the running time of cpu is : 2.3696s the running time of gpu is : 0 ...
- jQuery学习笔记(一):入门
jQuery学习笔记(一):入门 一.JQuery是什么 JQuery是什么?始终是萦绕在我心中的一个问题: 借鉴网上同学们的总结,可以从以下几个方面观察. 不使用JQuery时获取DOM文本的操 ...
- ANE接入平台心得记录(安卓)
开发环境:FlashBuilder4.7 AIR13.0 Eclipse 由于我懒得陪安卓的开发环境所以我下载了包含安卓SDK Manager的Eclipse,其实直接用FlashBuilder开发A ...