HDFS的API流操作
包括文件上传、下载、重命名、删除等
Before和After
Before用于获取文件信息
After用于关闭资源
可以减少代码量
@Before
public void before() throws IOException, InterruptedException {
fs = FileSystem.get(URI.create("hdfs://hadoop102:9000"),new Configuration(),"atguigu");
System.out.println("Before..........");
}
@After
public void after() throws IOException, InterruptedException {
fs.close();
System.out.println("after..........");
}
HDFS的文件上传
代码实现
@Test
public void put() throws IOException,InterruptedException{
//1.获取文件系统
Configuration configuration = new Configuration();
FileSystem fileSystem = FileSystem.get(URI.create("hdfs://hadoop102:9000"),configuration,"atguigu");
//2.执行上传操作,
fileSystem.copyFromLocalFile(new Path("D://test//1.txt"),new Path("/"));
//3.关闭资源
fileSystem.close();
}
HDFS文件下载
代码实现
@Test
public void get() throws IOException,InterruptedException{
//1.获取文件信息
Configuration configuration = new Configuration();
FileSystem fileSystem = FileSystem.get(URI.create("hdfs://hadoop102:9000"),configuration,"atguigu");
//2.执行下载操作
fileSystem.copyToLocalFile(new Path("/test"),new Path("d:\\"));
//关闭
fileSystem.close();
}
HDFS文件夹删除
需要注意这里删除的只能是文件夹,不能是文件
代码实现
@Test
public void delete() throws IOException, InterruptedException {
//执行删除操作
boolean delete =fs.delete(new Path("/test1.txt"), true);
if(delete){
System.out.println("删除成功");
}else{
System.out.println("删除失败");
}
}
HDFS重命名
代码实现
@Test
public void rename() throws IOException, InterruptedException {
FileSystem fileSystem = FileSystem.get(URI.create("hdfs://hadoop102:9000"), new Configuration(), "atguigu");
//执行重命名操作
fileSystem.rename(new Path("/test"),new Path("/test2"));
fileSystem.close();
}
文件或文件夹判断
@Test
public void ls() throws IOException {
FileStatus[] fileStatuses = fs.listStatus(new Path("/"));
for (FileStatus fileStatus : fileStatuses) {
if(fileStatus.isFile()){
System.out.println("以下是一个文件,以下是文件信息");
System.out.println(fileStatus.getPath());
}else{
System.out.println("这是一个文件夹");
System.out.println(fileStatus.getPath());
}
}
}
HDFS文件详情查看
查看文件名称、权限、长度、块信息
代码实现
@Test
public void testListFiles() throws IOException, InterruptedException, URISyntaxException{
// 1获取文件系统
Configuration configuration = new Configuration();
FileSystem fs = FileSystem.get(new URI("hdfs://hadoop102:9000"), configuration, "atguigu");
// 2 获取文件详情
RemoteIterator<LocatedFileStatus> listFiles = fs.listFiles(new Path("/"), true);
while(listFiles.hasNext()){
LocatedFileStatus status = listFiles.next();
// 输出详情
// 文件名称
System.out.println(status.getPath().getName());
// 长度
System.out.println(status.getLen());
// 权限
System.out.println(status.getPermission());
// 分组
System.out.println(status.getGroup());
// 获取存储的块信息
BlockLocation[] blockLocations = status.getBlockLocations();
for (BlockLocation blockLocation : blockLocations) {
// 获取块存储的主机节点
String[] hosts = blockLocation.getHosts();
for (String host : hosts) {
System.out.println(host);
}
}
System.out.println("-----------班长的分割线----------");
}
// 3 关闭资源
fs.close();
}