初识HDFS----编程实现对HDFS文件的读写(GetMerge和PutMerge)
目标:
1、了解hdfs常规的命令
2、在配置好hadoop开发环境的eclipse中编程实现Merger功能,实现从云端 (HDFS)中一个包含多个文件的路径(文件夹),将所有文件合并后保存到本地,或从云端合并文件下载到本地。
首先我们启动hadoop,运行jps验证启动成功。
一、了解HDFS命令
在终端输入hdfs dfs
回车,可以看到关于HDFS操作的所有命令。我们可以根据名字发现与我们Linux下常用的命令类似,如cat,chmod,ls等都相同;其它如copyFromLocal也可见名知意。
如查看HDFS中的/user/chengzhijun中的所有文件,在终端输入hdfs dfs -ls /user/chegnzhijun
关于dfs的更多命令可以参阅这里HDFS中dfs 命令.
二、实现本地和HDFS文本文件的合并上传下载。
1:本地创建文件
首先在本地的/home/chengzhijun/cloud/merge中创建merge1、merge2、merge3 三个文本文件,分别写入:
这是第一个文档,hello merge1!
这是第二个文档,hello merge2!
这是第三个文档,hello merge3!
2:编程将上面三个文本文件内容合并后上传到HDFS中
代码如下,注释中我都尽量有详细的说明,其中uri为本地上传到HDFS中的文件(会自动创建)
public static void main(String[] args) throws IOException, URISyntaxException {
Configuration conf = new Configuration();
String uri = "hdfs://localhost:9000/user/hadoop/merge/merge"; //三个文本合并后上传到HDFS中的位置
Path hdfsDir = new Path(uri);
Path localDir = new Path("/home/chengzhijun/cloud/merge");
FileSystem hdfs = FileSystem.get(new URI(uri), conf);
FileSystem local = FileSystem.getLocal(conf);
FileStatus[] files = local.listStatus(localDir); //本地merge目录下的所有文件信息
FSDataOutputStream out = hdfs.create(hdfsDir); //在HDFS中创建merge文件
for(int i=0;i<files.length;i++) {
FSDataInputStream in = local.open(files[i].getPath()); //一个个文件打开为输出流进行读取
byte[] bytes = new byte[256];
int off = 0;
while( (off = in.read(bytes)) > 0) {
out.write(bytes, 0, off); //写入到输出流
}
IOUtils.closeStream(in);
}
IOUtils.closeStream(out);
}
结果如下:
在HDFS上的/user/hadoop/merge下成功生成了merge,内容为本地三个merge文件合并的内容。
三、编程将HDFS中某个目录下所有文件合并后下载到本地,代码类似。
1、如上创建三个文件,保存在hdfs的/user/hadoop/merge目录下。
2、运行如下代码,其实与上面的差不多,uri为hdfs中我们要下载的文件夹,localFile为我们要保存到的文件。
public static void main(String[] args) throws IOException, URISyntaxException {
Configuration conf = new Configuration();
String uri = "hdfs://localhost:9000/user/hadoop/merge";
Path hdfsDir = new Path(uri);
Path localFile = new Path("/home/chengzhijun/cloud/merge/cloudMerge.txt");
FileSystem hdfs = FileSystem.get(new URI(uri), conf);
FileSystem localFS = FileSystem.getLocal(conf);
FileStatus[] files = hdfs.listStatus(hdfsDir);
FSDataOutputStream out = localFS.create(localFile);
for(int i=0;i<files.length;i++) {
FSDataInputStream in = hdfs.open(files[i].getPath());
byte[] bytes = new byte[256];
int len = 0;
while( (len = in.read(bytes)) > 0) {
out.write(bytes, 0, len);
}
IOUtils.closeStream(in);
}
IOUtils.closeStream(out);
}
3、如图,在/home/chengzhijun/cloud/merge/中生成了cloudMerge.txt,保存了三个文本文件合并的内容。