1. 在IDEA中创建一个Maven工程HdfsClientDemo。请注意要选择Maven项目。
2. 在pom.xml中补充相应的依赖坐标+日志添加。
<dependencies>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-client</artifactId>
<version>3.1.3</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.30</version>
</dependency>
</dependencies>
这一步中的hadoop-client要和我们前面客户端准备中下载的hadoop保持一致。
3. 配置日志信息。在项目的src/main/resources目录下,新建一个文件,命名为“log4j.properties”,在文件中填入如下配置信息:
log4j.rootLogger=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n
log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.File=target/spring.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n
4. 创建包及对应的类。我们创建一个包为example.org,并在下面创建HdfsClient类。编写代码如下:
public class HdfsClient {
@Test
public void testMkdirs() throws IOException, URISyntaxException, InterruptedException {
// 1 获取文件系统
Configuration configuration = new Configuration();
FileSystem fs = FileSystem.get(new URI("hdfs://hadoop100:8020"), configuration,"root");
// 2 创建目录
fs.mkdirs(new Path("/xiyou/huaguoshan/"));
// 3 关闭资源
fs.close();
}
}
5. 执行程序
如果程序执行没有错误,就会在HDFS中创建对应的文件目录,大家可以去服务器端查看。客户端去操作HDFS时,是有一个用户身份的。默认情况下,HDFS客户端API会从采用Windows默认用户访问HDFS,会报权限异常错误。所以在访问HDFS时,一定要配置用户。
package org.example;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class HdfsClient {
private FileSystem fs;
@Before
public void init() throws URISyntaxException, IOException, InterruptedException {
// 1 获取文件系统
Configuration configuration = new Configuration();
// FileSystem fs = FileSystem.get(new URI("hdfs://hadoop102:8020"), configuration);
fs = FileSystem.get(new URI("hdfs://hadoop100:8020"), configuration,"root");
}
@After
public void close() throws IOException {
fs.close();
}
@Test
public void testMkdirs() throws IOException, URISyntaxException, InterruptedException {
// 2 创建目录
fs.mkdirs(new Path("/xiyou/huaguoshan11/"));
}
}