一. 引入POM依赖
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-client</artifactId>
<version>3.1.3</version>
</dependency>
二. 编写API
package com.xx;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.*;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
public class Main {
FileSystem fileSystem;
@Before
public void init() throws URISyntaxException, IOException, InterruptedException {
URI uri = new URI("hdfs://hadoop102:8020");
Configuration configuration = new Configuration();
fileSystem = FileSystem.get(uri, configuration, "root");
}
@Test
public void mkdirs() throws IOException {
fileSystem.mkdirs(new Path("/hadoop-api"));
fileSystem.close();
}
@Test
public void upload() throws IOException {
fileSystem.copyFromLocalFile(false, true, new Path("D:\\Study\\大数据\\hadoop\\笔记\\test.txt"), new Path("/hadoop-api"));
fileSystem.close();
}
@Test
public void download() throws IOException {
fileSystem.copyToLocalFile(false, new Path("/hadoop-api/test.txt"), new Path("D:\\Study\\大数据\\hadoop\\笔记"));
fileSystem.close();
}
@Test
public void delete() throws IOException {
fileSystem.delete(new Path("/hadoop-api"), true);
fileSystem.close();
}
@Test
public void moveFile() throws IOException {
fileSystem.rename(new Path("/hadoop-api/test.txt"), new Path("/hadoop-api/test-change.txt"));
fileSystem.close();
}
@Test
public void fileDetail() throws IOException {
RemoteIterator<LocatedFileStatus> listFiles = fileSystem.listFiles(new Path("/"), true);
while (listFiles.hasNext()) {
LocatedFileStatus file = listFiles.next();
System.out.println(file.getPath());
System.out.println(file.getPath().getName());
System.out.println(file.getPermission());
System.out.println(file.getOwner());
System.out.println(file.getGroup());
System.out.println(file.getLen());
System.out.println(file.getModificationTime());
System.out.println(file.getReplication());
System.out.println(file.getBlockSize());
System.out.println("======================");
}
}
@Test
public void judge() throws IOException {
FileStatus[] fileStatuses = fileSystem.listStatus(new Path("/"));
for (FileStatus fileStatus : fileStatuses) {
if (fileStatus.isFile()) {
System.out.println("这是一个文件");
} else {
System.out.println("这是一个目录");
}
}
}
}