分布式文件系统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);
}
}

HDFS文件目录操作代码的更多相关文章

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

    这篇文章主要介绍了使用hadoop的API对HDFS上的文件访问,其中包括上传文件到HDFS上.从HDFS上下载文件和删除HDFS上的文件,需要的朋友可以参考下hdfs文件操作操作示例,包括上传文件到 ...

  2. Hadoop---Java-API对HDFS的操作

    Java-API对HDFS的操作 哈哈哈哈,深夜来一波干货哦!!! Java-PAI对hdfs的操作,首先我们建一个maven项目,我主要说,我们可以通过Java代码来对HDFS的具体信息的打印,然后 ...

  3. Hadoop JAVA HDFS客户端操作

    JAVA HDFS客户端操作 通过API操作HDFS org.apache.logging.log4jlog4j-core2.8.2org.apache.hadoophadoop-common${ha ...

  4. Hadoop之HDFS文件操作常有两种方式(转载)

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

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

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

  6. Scala 深入浅出实战经典 第39讲:ListBuffer、ArrayBuffer、Queue、Stack操作代码实战

    王家林亲授<DT大数据梦工厂>大数据实战视频 Scala 深入浅出实战经典(1-64讲)完整视频.PPT.代码下载:百度云盘:http://pan.baidu.com/s/1c0noOt6 ...

  7. Scala深入浅出实战经典之 List的foldLeft、foldRight、sort操作代码实战

     Scala 深入浅出实战经典(1-64讲)完整视频.PPT.代码下载:百度云盘:http://pan.baidu.com/s/1c0noOt6 腾讯微云:http://url.cn/TnGbdC 3 ...

  8. php文件夹与文件目录操作函数

    在php中一些常用的文件夹/文件目录操作函数总结. php文件夹操作函数 string basename ( string path [, string suffix] ) 给出一个包含有指向一个文件 ...

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

    写在前面: 1,<你一定要知道的关于Linux文件目录操作的12个常用命令>是楼主收集的关于Linux文件目录操作最常用的命令,包括文件或目录的新建.拷贝.移动.删除.查看等,是开发人员操 ...

随机推荐

  1. 异步函数Demo

    private static async Task<String> IssueClientRequestAsync(string serverName, string message) { ...

  2. linux——常用命令

    学习linux命令地址: 学习命令地址,可参考http://linux.51yip.com/ 在文件中搜索指定字符串 grep -i "requirepass" redis.con ...

  3. p4434 [COCI2017-2018#2] ​​Usmjeri

    思路 并查集的好题 考虑到求满足条件限制的方案数,显然观察样例可知结果就是2^x,x是互不影响的边的集合数量 然后考虑如何求互不影响的边的集合数量 可以使用并查集,用i和i+n表示这个点的父亲连向它的 ...

  4. ACM-ICPC 2017 沈阳赛区现场赛 G. Infinite Fraction Path && HDU 6223(BFS)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=6223 参考题解:https://blog.csdn.net/qq_40482495/article/d ...

  5. BZOJ 3658: Jabberwocky (双向链表+BIT)

    题意 平面上有n个点,每个点有k种颜色中的一个.你可以选择一条水平的线段获得在其上方或其下方的所有点,请求出你最多能够得到多少点,使得获得的点并不包含所有的颜色. 分析 线段可以向上向下,那么我们只考 ...

  6. Codeforces Round #588 (Div. 2) C. Anadi and Domino(思维)

    链接: https://codeforces.com/contest/1230/problem/C 题意: Anadi has a set of dominoes. Every domino has ...

  7. 菜鸟刷面试题(五、Java容器篇)

    目录: java 容器都有哪些? Collection 和 Collections 有什么区别? List.Set.Map 之间的区别是什么? HashMap 和 Hashtable 有什么区别? 如 ...

  8. [Luogu] trip

    https://www.luogu.org/problemnew/show/T28848#sub #include <iostream> #include <cstdio> u ...

  9. Noip2011 提高组 Day1 T3 Mayan游戏

    题目描述 Mayan puzzle是最近流行起来的一个游戏.游戏界面是一个 7 行5 列的棋盘,上面堆放着一些方块,方块不能悬空堆放,即方块必须放在最下面一行,或者放在其他方块之上.游戏通关是指在规定 ...

  10. Linux之GDB命令(二)

    gdb命令: 前提条件:可执行文件必须包含调试信息 gcc -g gdb 文件名 –启动gdb调试 查看代码命令   当前文件:     list 行号(函数名)   指定文件:     list 文 ...