分布式文件系统HDFS中对文件/目录的相关操作代码,整理了一下,大概包括以下部分:

  • 文件夹的新建、删除、重命名
  • 文件夹中子文件和目录的统计
  • 文件的新建及显示文件内容
  • 文件在local和remote间的相互复制
  • 定位文件在HDFS中的位置,以及副本存放的主机
  • HDFS资源使用情况

1. 新建文件夹

public void mkdirs(String folder) throws IOException {Path path = new Path(folder);FileSystem fs = FileSystem.get(URI.create(hdfsPath), conf);if (!fs.exists(path)) {fs.mkdirs(path);System.out.println("Create: " + folder);}fs.close();
}

2. 删除文件夹

public void rmr(String folder) throws IOException {Path path = new Path(folder);FileSystem fs = FileSystem.get(URI.create(hdfsPath), conf);fs.deleteOnExit(path);System.out.println("Delete: " + folder);fs.close();
}

3. 文件重命名

public void rename(String src, String dst) throws IOException {Path name1 = new Path(src);Path name2 = new Path(dst);FileSystem fs = FileSystem.get(URI.create(hdfsPath), conf);fs.rename(name1, name2);System.out.println("Rename: from " + src + " to " + dst);fs.close();
}

4. 列出文件夹中的子文件及目录

public void ls(String folder) throws IOException {Path path = new Path(folder);FileSystem fs = FileSystem.get(URI.create(hdfsPath), conf);FileStatus[] list = fs.listStatus(path);System.out.println("ls: " + folder);System.out.println("==========================================================");for (FileStatus f : list) {System.out.printf("name: %s, folder: %s, size: %d\n", f.getPath(), f.isDirectory(), f.getLen());}System.out.println("==========================================================");fs.close();
}

5. 创建文件,并添加内容

public void createFile(String file, String content) throws IOException {FileSystem fs = FileSystem.get(URI.create(hdfsPath), conf);byte[] buff = content.getBytes();FSDataOutputStream os = null;try {os = fs.create(new Path(file));os.write(buff, 0, buff.length);System.out.println("Create: " + file);} finally {if (os != null)os.close();}fs.close();
}

6. 将local数据复制到remote

public void copyFile(String local, String remote) throws IOException {FileSystem fs = FileSystem.get(URI.create(hdfsPath), conf);fs.copyFromLocalFile(new Path(local), new Path(remote));System.out.println("copy from: " + local + " to " + remote);fs.close();
}

7. 将remote数据下载到local

public void download(String remote, String local) throws IOException {Path path = new Path(remote);FileSystem fs = FileSystem.get(URI.create(hdfsPath), conf);fs.copyToLocalFile(path, new Path(local));System.out.println("download: from" + remote + " to " + local);fs.close();
}

8. 显示文件内容

    public String cat(String remoteFile) throws IOException {Path path = new Path(remoteFile);FileSystem fs = FileSystem.get(URI.create(hdfsPath), conf);FSDataInputStream fsdis = null;System.out.println("cat: " + remoteFile);OutputStream baos = new ByteArrayOutputStream();String str = null;try {fsdis = fs.open(path);IOUtils.copyBytes(fsdis, baos, 4096, false);str = baos.toString();} finally {IOUtils.closeStream(fsdis);fs.close();}System.out.println(str);return str;}

9. 定位一个文件在HDFS中存储的位置,以及多个副本存储在集群哪些节点上

public void location() throws IOException {String folder = hdfsPath + "create/";String file = "t2.txt";FileSystem fs = FileSystem.get(URI.create(hdfsPath), new Configuration());FileStatus f = fs.getFileStatus(new Path(folder + file));BlockLocation[] list = fs.getFileBlockLocations(f, 0, f.getLen());System.out.println("File Location: " + folder + file);for (BlockLocation bl : list) {String[] hosts = bl.getHosts();for (String host : hosts) {System.out.println("host:" + host);}}fs.close();
}

10. 获取HDFS集群存储资源使用情况

public void getTotalCapacity() {try {FileSystem fs = FileSystem.get(URI.create(hdfsPath), conf);FsStatus fsStatus = fs.getStatus();System.out.println("总容量:" + fsStatus.getCapacity());System.out.println("使用容量:" + fsStatus.getUsed());System.out.println("剩余容量:" + fsStatus.getRemaining());} catch (IOException e) {e.printStackTrace();}
}

完整代码

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.BlockLocation;
import org.apache.hadoop.fs.ContentSummary;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
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.io.IOUtils;
import org.apache.hadoop.mapred.JobConf;/*
* HDFS工具类
*
*/
public class Hdfs {private static final String HDFS = "hdfs://10.20.14.47:8020/";public Hdfs(Configuration conf) {this(HDFS, conf);}public Hdfs(String hdfs, Configuration conf) {this.hdfsPath = hdfs;this.conf = conf;}private String hdfsPath;private Configuration conf;public static void main(String[] args) throws IOException {JobConf conf = config();Hdfs hdfs = new Hdfs(conf);hdfs.createFile("/create/t2.txt", "12");hdfs.location();}public static JobConf config() {JobConf conf = new JobConf(Hdfs.class);conf.setJobName("HdfsDAO");conf.addResource("classpath:/hadoop/core-site.xml");conf.addResource("classpath:/hadoop/hdfs-site.xml");conf.addResource("classpath:/hadoop/mapred-site.xml");return conf;}/** 创建文件夹*/public void mkdirs(String folder) throws IOException {Path path = new Path(folder);FileSystem fs = FileSystem.get(URI.create(hdfsPath), conf);if (!fs.exists(path)) {fs.mkdirs(path);System.out.println("Create: " + folder);}fs.close();}/** 删除文件夹*/public void rmr(String folder) throws IOException {Path path = new Path(folder);FileSystem fs = FileSystem.get(URI.create(hdfsPath), conf);fs.deleteOnExit(path);System.out.println("Delete: " + folder);fs.close();}/** 文件重命名*/public void rename(String src, String dst) throws IOException {Path name1 = new Path(src);Path name2 = new Path(dst);FileSystem fs = FileSystem.get(URI.create(hdfsPath), conf);fs.rename(name1, name2);System.out.println("Rename: from " + src + " to " + dst);fs.close();}/** 列出文件夹中的子文件及目录*/public void ls(String folder) throws IOException {Path path = new Path(folder);FileSystem fs = FileSystem.get(URI.create(hdfsPath), conf);FileStatus[] list = fs.listStatus(path);System.out.println("ls: " + folder);System.out.println("==========================================================");for (FileStatus f : list) {System.out.printf("name: %s, folder: %s, size: %d\n", f.getPath(), f.isDirectory(), f.getLen());}System.out.println("==========================================================");fs.close();}/** 创建文件,并添加内容*/public void createFile(String file, String content) throws IOException {FileSystem fs = FileSystem.get(URI.create(hdfsPath), conf);byte[] buff = content.getBytes();FSDataOutputStream os = null;try {os = fs.create(new Path(file));os.write(buff, 0, buff.length);System.out.println("Create: " + file);} finally {if (os != null)os.close();}fs.close();}/** 将local的数据复制到remote*/public void copyFile(String local, String remote) throws IOException {FileSystem fs = FileSystem.get(URI.create(hdfsPath), conf);fs.copyFromLocalFile(new Path(local), new Path(remote));System.out.println("copy from: " + local + " to " + remote);fs.close();}/** 将remote数据下载到local*/public void download(String remote, String local) throws IOException {Path path = new Path(remote);FileSystem fs = FileSystem.get(URI.create(hdfsPath), conf);fs.copyToLocalFile(path, new Path(local));System.out.println("download: from" + remote + " to " + local);fs.close();}/** 显示文件内容*/public String cat(String remoteFile) throws IOException {Path path = new Path(remoteFile);FileSystem fs = FileSystem.get(URI.create(hdfsPath), conf);FSDataInputStream fsdis = null;System.out.println("cat: " + remoteFile);OutputStream baos = new ByteArrayOutputStream();String str = null;try {fsdis = fs.open(path);IOUtils.copyBytes(fsdis, baos, 4096, false);str = baos.toString();} finally {IOUtils.closeStream(fsdis);fs.close();}System.out.println(str);return str;}/** 定位一个文件在HDFS中存储的位置,以及多个副本存储在集群哪些节点上*/public void location() throws IOException {String folder = hdfsPath + "create/";String file = "t2.txt";FileSystem fs = FileSystem.get(URI.create(hdfsPath), new Configuration());FileStatus f = fs.getFileStatus(new Path(folder + file));BlockLocation[] list = fs.getFileBlockLocations(f, 0, f.getLen());System.out.println("File Location: " + folder + file);for (BlockLocation bl : list) {String[] hosts = bl.getHosts();for (String host : hosts) {System.out.println("host:" + host);}}fs.close();}/** 获取HDFS资源使用情况*/public void getTotalCapacity() {try {FileSystem fs = FileSystem.get(URI.create(hdfsPath), conf);FsStatus fsStatus = fs.getStatus();System.out.println("总容量:" + fsStatus.getCapacity());System.out.println("使用容量:" + fsStatus.getUsed());System.out.println("剩余容量:" + fsStatus.getRemaining());} catch (IOException e) {e.printStackTrace();}}/** 获取某文件中包含的目录数,文件数,及占用空间大小*/public void getContentSummary(String path) {ContentSummary cs = null;try {FileSystem fs = FileSystem.get(URI.create(hdfsPath), conf);cs = fs.getContentSummary(new Path(path));} catch (Exception e) {e.printStackTrace();}// 目录数Long directoryCount = cs.getDirectoryCount();// 文件数Long fileCount = cs.getFileCount();// 占用空间Long length = cs.getLength();System.out.println("目录数:" + directoryCount);System.out.println("文件数:" + fileCount);System.out.println("占用空间:" + length);}
}

View Code

转载于:https://www.cnblogs.com/walker-/p/9768834.html

HDFS文件目录操作代码相关推荐

  1. HDFS的API调用,创建Maven工程,创建一个非Maven工程,HDFS客户端操作数据代码示例,文件方式操作和流式操作

    1. HDFS的java操作 hdfs在生产应用中主要是客户端的开发,其核心步骤是从hdfs提供的api中构造一个HDFS的访问客户端对象,然后通过该客户端对象操作(增删改查)HDFS上的文件 1.1 ...

  2. hadoop的hdfs文件操作实现上传文件到hdfs

    hdfs文件操作操作示例,包括上传文件到HDFS上.从HDFS上下载文件和删除HDFS上的文件,大家参考使用吧 复制代码代码如下: import org.apache.hadoop.conf.Conf ...

  3. java实现英文文件单词搜索系统_java对于目录下文件的单词查找操作代码实现

    这篇文章主要介绍了java对于目录下文件的单词查找操作代码实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 写入文件的目录.代码通过找目录下的文件 ...

  4. adc 接收cube_官方的stm32cube软件教程实例ADC操作代码(官方自带的,可以无视

    该楼层疑似违规已被系统折叠 隐藏此楼查看此楼 官方的stm32cube软件教程实例ADC操作代码(官方自带的,可以无视),看不懂怎么用的可以等本贴吧更新图片教程,现在就是凑帖子数量,完成转职的,请谅解 ...

  5. HDFS简单介绍及用C语言訪问HDFS接口操作实践

    一.概述 近年来,大数据技术如火如荼,怎样存储海量数据也成了当今的热点和难点问题,而HDFS分布式文件系统作为Hadoop项目的分布式存储基础,也为HBASE提供数据持久化功能,它在大数据项目中有很广 ...

  6. paip.文件目录操作uAPI php python java对照

    paip.文件目录操作uAPI php python java对照 chdir -- 改变目录 chroot -- 改变根目录 dir -- directory 类 closedir -- 关闭目录句 ...

  7. 将数据库的操作代码从servlet中剥离,封装到DAO中

    工厂设计模式是所有设计模式中最简单的设计模式!!!(就是通过工厂来创建一些对象) 工厂模式的典型应用场景:创建对象(当我们感觉到创建对象是件很痛苦的事,会用工厂模式) 工厂模式:简单工厂,工厂方法,抽 ...

  8. 你一定要知道的关于Linux文件目录操作的12个常用命令

    博客园 首页 新随笔 联系 管理 订阅 随笔- 26  文章- 1  评论- 18  你一定要知道的关于Linux文件目录操作的12个常用命令 转自:http://www.cnblogs.com/yo ...

  9. Hadoop之HDFS文件操作

    摘要:Hadoop之HDFS文件操作常有两种方式,命令行方式和JavaAPI方式.本文介绍如何利用这两种方式对HDFS文件进行操作. 关键词:HDFS文件    命令行     Java API HD ...

最新文章

  1. power bi可视化表_如何使用Power BI可视化数据?
  2. 计算机的两个基本能力是存储程序,【2012年职称计算机模拟题(55)】- 环球网校...
  3. wireshark 十六进制过滤_CTF流量分析之wireshark使用
  4. vs2019配置OpenGL
  5. lpsolve java_如何使用LpSolve在R中设置线性编程优化?
  6. 电脑word在哪_焦作市周边商务电脑办公入门培训
  7. 如何将汇编语言转换为c语言,如何把汇编语言转换成C语言
  8. PS进阶抠图详解(可以处理头发)
  9. import image的坑
  10. 华为鸿蒙宣传图,VIVO 联动华为?官方宣传图出现华为智联,为鸿蒙合作埋下伏笔...
  11. Android全面屏状态栏适配
  12. Spring-aop面向切面
  13. tabIndex的用途
  14. 亚马逊SP-API对接JAVA版(amazon selling-partner)
  15. 浙江八年级 python_今年9月起,浙江八年级新增Python编程课程
  16. 【文献阅读笔记】BoT-SORT: Robust Associations Multi-Pedestrian Tracking
  17. 编译原理的FIRST、FOLLOW、FIRSTVT、LASTVT的求法总结
  18. Linux基本知识点整理
  19. JAVA UUID 获取方法
  20. 前端判断扫码的客户端是微信还是支付宝?

热门文章

  1. 全国计算机等级考试题库二级C操作题100套(第63套)
  2. TreeMap实现排序
  3. 光纤测试时怎么选择对应项目的测试标准及测试仪?
  4. 设备的分配与调度简单方案_连铸生产调度与动态重调度的优化与研究-3,炼钢技术(3)原创...
  5. oracle 安全备份与rman_Oracle 11g下使用RMAN进行备份和恢复操作(一)
  6. logisim输出变成红色的e_新车实拍解析 福特Mustang Mach-E亮点实拍图解
  7. 用扫地机器人楼下吵吗_扫地机器人到底好不好用?说说我两年的使用体验!
  8. windows比linux差在哪,怎么让新手理解Linux比Windows好在哪里!
  9. 鸿蒙系统支持980,鸿蒙手机上线时间 鸿蒙系统支持哪些手机2021最新汇总
  10. Spark List组件滚动条加事件使datalist数据发生变化