将建立链接放在before(),关闭链接放在after()
package xyz.youngit.hdfs;
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;
public class HDFSClient {
FileSystem fileSystem;
/*
* @description 建立链接
* @param []
* @return void
*/
@Before
public void before() throws IOException, InterruptedException {
Configuration configuration = new Configuration();
// configuration.set("dfs.replication","2");
//1.新建HDFS对象
fileSystem = FileSystem.get(URI.create("hdfs://hadoop129:8020"),
configuration,"youngit");
}
/*
* @description 上传
* @param []
* @return void
*/
@Test
public void put() throws IOException, InterruptedException {
//2.操作集群
fileSystem.copyFromLocalFile(new Path("D:\\testFolder"),
new Path("/"));
}
// boolean delSrc 指是否将原文件删除
// Path src 指要下载的文件路径
// Path dst 指将文件下载到的路径
// boolean useRawLocalFileSystem 是否开启文件校验
@Test
public void down() throws IOException, InterruptedException {
//2.操作集群
fileSystem.copyToLocalFile(false,new Path("/test.txt"),
new Path("d:/test1.txt"),true);
}
/*
* @description 删除操作
* @param []
* @return void
*/
@Test
public void delete() throws IOException, InterruptedException {
//2.操作集群
fileSystem.delete(new Path("/test2.txt"),true);
}
/*
* @description 文件名更改
* @param []
* @return void
*/
@Test
public void testRename() throws IOException, InterruptedException {
//2.操作集群
fileSystem.rename(new Path("/test.txt"),new Path("/test1.txt"));
}
/*
* @description 查看文件名称、权限、长度、块信息
* @param []
* @return void
*/
@Test
public void testListFiles() throws IOException {
// 2 获取文件详情
RemoteIterator<LocatedFileStatus> listFiles = fileSystem.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("-----------分割线------------");
}
}
/*
* @description 文件和文件夹的判断
* @param []
* @return void
*/
@Test
public void testListStatus() throws IOException, InterruptedException{
// 2 判断是文件还是文件夹
FileStatus[] listStatus = fileSystem.listStatus(new Path("/"));
for (FileStatus fileStatus : listStatus) {
// 如果是文件
if (fileStatus.isFile()) {
System.out.println("文件:"+fileStatus.getPath().getName());
}else {
System.out.println("文件夹:"+fileStatus.getPath().getName());
}
}
}
@After
public void after() throws IOException {
//3.关闭资源
fileSystem.close();
}
}
|