FSTest.java
@Slf4j
public class FSTest {
public static FileSystem fileSystem;
@Before
public void init() throws URISyntaxException, IOException, InterruptedException {
fileSystem = FileSystem.get(new URI("hdfs://hadoop01:9000"), new Configuration(), "root");
}
@After
public void close() throws IOException {
fileSystem.close();
}
@Test
public void showRootFiles() throws Exception {
RemoteIterator<LocatedFileStatus> files = fileSystem.listFiles(new Path("/"), false);
while (files.hasNext()) {
LocatedFileStatus fileStatus = files.next();
Path path = fileStatus.getPath();
String name = path.getName();
log.info("{} -> {}", path, name);
}
}
@Test
public void testCopyFromLocalFile() throws Exception {
Path src = new Path("E:\\work\\test.txt");
Path dst = new Path("/");
fileSystem.copyFromLocalFile(src, dst);
}
@Test
public void testDelete() throws Exception {
Path dst = new Path("/test.txt");
fileSystem.delete(dst, true);
}
@Test
public void testUploadUseStream() throws Exception {
FileInputStream fis = new FileInputStream("E:\\work\\test.txt");
Path path = new Path("/test.txt");
FSDataOutputStream fos = fileSystem.create(path);
IOUtils.copy(fis, fos);
}
@Test
public void testCopyToLocalFile() throws Exception {
fileSystem.copyToLocalFile(false, new Path("/test.txt"), new Path("E:\\work\\test2.txt"), true);
}
}
pom.xml
<dependencies>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-common</artifactId>
<version>3.3.5</version>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-hdfs</artifactId>
<version>3.3.5</version>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-client</artifactId>
<version>3.3.5</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>2.0.7</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>2.0.7</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.26</version>
<scope>provided</scope>
</dependency>
</dependencies>