HDFS的API操作
对于hdfs的shell命令操作在前一篇的笔记中已经学习,最近对hdfs的API操作进行了学习,主要包括:
1、hadoop的连接和关闭
2、文件目录的创建
3、文件上传
4、文件下载
5、文件删除
6、文件的更名和移动
7、获取文件详细信息
8、判断是文件还是目录
全部操作代码如下:
package com.yasin.hdfs;
/* 1.获取一个客户端对象 2.执行相关的操作命令 3.关闭资源 */
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
public class HdfsClient {
private FileSystem fs;
/* // 快捷键 ctrl + p获取函数的参数说明 alt+enter抛出异常 (ctrl+alt+l:格式化) */
@Before
public void init() throws URISyntaxException, IOException, InterruptedException {
//连接集群nn地址
URI uri = new URI("hdfs://hadoop102:8020");
//创建一个配置文件
Configuration configuration = new Configuration();
//获取到了客户端对象
String usr = "yasin";
fs = FileSystem.get(uri, configuration, usr);
}
@After
public void close() throws IOException {
//关闭资源
fs.close();
}
//创建一个目录
@Test
public void testmkdir() throws URISyntaxException, IOException, InterruptedException {
fs.mkdirs(new Path("/xiyou/huaguoshan3"));
}
//文件上传
@Test
public void testPut() throws IOException {
fs.copyFromLocalFile(false, true, new Path("D:\\sunwukong.txt"), new Path("hdfs://hadoop102:/xiyou/huaguoshan"));
}
//文件下载
@Test
public void testGet() throws IOException {
fs.copyToLocalFile(false, new Path("hdfs://hadoop102/xiyou/"), new Path("D:\\"), true);
}
//文件删除
@Test
public void testDel() throws IOException {
//删除文件
//fs.delete(new Path("hdfs://hadoop102/jdk-8u212-linux-x64.tar.gz"),false);
//删除空目录
fs.delete(new Path("hdfs://hadoop102:/xiyou/"), true);
}
//文件更名和移动
@Test
public void testmv() throws IOException {
//对文件名修改
//fs.rename(new Path("/input/word.txt"),new Path("/input/ss.txt"));
//文件的移动和更名
//fs.rename(new Path("/input/ss.txt"),new Path("/cls.txt"));
//目录的更名
fs.rename(new Path("/input"), new Path("/output"));
}
// 获取文件详细信息
@Test
public void fileDetail() throws IOException {
//获取所有文件信息
RemoteIterator<LocatedFileStatus> listFiles = fs.listFiles(new Path("/"), true);
//遍历文件
while (listFiles.hasNext()) {
LocatedFileStatus fileStatus = listFiles.next();
System.out.println("========" + fileStatus.getPath() + "======");
System.out.println(fileStatus.getPermission());
System.out.println(fileStatus.getOwner());
System.out.println(fileStatus.getGroup());
System.out.println(fileStatus.getModificationTime());
System.out.println(fileStatus.getBlockSize());
System.out.println(fileStatus.getPath().getName());
System.out.println(fileStatus.getReplication());
// 获取块信息
BlockLocation[] blockLocations = fileStatus.getBlockLocations();
System.out.println(Arrays.toString(blockLocations));
}
}
//判断是文件夹还是文件
@Test
public void testfile() throws IOException {
FileStatus[] listStatus = fs.listStatus(new Path("/"));
for (FileStatus status : listStatus) {
if (status.isFile()) {
System.out.println("文件:" + status.getPath().getName());
} else {
System.out.println("路径:" + status.getPath().getName());
}
}
}
}
还没有评论,来说两句吧...