【HDFS】三、HDFS客户端操作(开发重点)

    科技2026-04-16  3

    一、HDFS客户端环境准备

    根据自己电脑的操作系统拷贝对应的编译后的hadoop jar包到非中文路径 hadoop 2.7.2下载

    配置HADOOP_HOME环境变量

    配置Path环境变量

    idea创建一个Maven工程HdfsClientDemo

    导入相应的依赖坐标+日志添加 在POM.XML中添加:

    <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>RELEASE</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.8.2</version> </dependency> <dependency> <groupId>org.apache.hadoop</groupId> <artifactId>hadoop-common</artifactId> <version>2.7.2</version> </dependency> <dependency> <groupId>org.apache.hadoop</groupId> <artifactId>hadoop-client</artifactId> <version>2.7.2</version> </dependency> <dependency> <groupId>org.apache.hadoop</groupId> <artifactId>hadoop-hdfs</artifactId> <version>2.7.2</version> </dependency> <dependency> <groupId>jdk.tools</groupId> <artifactId>jdk.tools</artifactId> <version>1.8</version> <scope>system</scope> <systemPath>${JAVA_HOME}/lib/tools.jar</systemPath> </dependency> </dependencies>

    注意:如果Eclipse/Idea打印不出日志,在控制台上只显示:

    1.log4j:WARN No appenders could be found for logger (org.apache.hadoop.util.Shell). 2.log4j:WARN Please initialize the log4j system properly. 3.log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.

    需要在项目的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 创建包名:com.until.hdfs创建类 public class HdfsClient { @Test public void put() throws IOException, InterruptedException { FileSystem fileSystem = FileSystem.get(URI.create("hdfs://hadoop200:9000"), new Configuration()); fileSystem.copyFromLocalFile(new Path("d:\\1.txt"),new Path("/user/hadoop")); fileSystem.close(); } }

    此处可能会报权限问题,解决办法如下: Permission denied: user=administrator, access=WRITE, inode=“/“:root:supergroup:drwxr-xr-x 8.执行程序 执行成功显示:

    Process finished with exit code 0

    二、HDFS的API操作

    HDFS文件操作 1.1 编写源代码 /** * @ClassName HdfsClient * @Description TODO * @Author rick2 * @Date 2020/10/9 22:35 * @Version 1.0 */ public class HdfsClient { private FileSystem fileSystem; @Before public void before() throws IOException, InterruptedException { fileSystem = FileSystem.get(URI.create("hdfs://hadoop200:9000"), new Configuration(), "hadoop"); } /** * 上传文件 * @throws IOException * @throws InterruptedException */ @Test public void put() throws IOException, InterruptedException { fileSystem.copyFromLocalFile(new Path("d:\\1.txt"), new Path("/user/hadoop")); } /** * 重命名文件名 * @throws IOException */ @Test public void rename() throws IOException { fileSystem.rename(new Path("/user/hadoop/1.txt"), new Path("/user/hadoop/2.txt")); } /** * 删除文件,true为递归删除 * @throws IOException */ @Test public void delete() throws IOException { boolean bIsDelete = fileSystem.delete(new Path("/user/hadoop/2.txt"), true); if (bIsDelete){ System.out.println("删除成功"); }else { System.out.println("删除失败"); } } /** * 文件详情查看,true为递归 * @throws IOException */ @Test public void listFiles() throws IOException { RemoteIterator<LocatedFileStatus> listFiles = fileSystem.listFiles(new Path("/user/hadoop"), true); while (listFiles.hasNext()){ LocatedFileStatus fileStatus = listFiles.next(); //输出详情 //文件名称 System.out.println(fileStatus.getPath().getName()); //长度 System.out.println(fileStatus.getLen()); //权限 System.out.println(fileStatus.getPermission()); //分组 System.out.println(fileStatus.getGroup()); //获取存储的块信息 BlockLocation[] blockLocations = fileStatus.getBlockLocations(); for (BlockLocation blockLocation :blockLocations){ String[] hosts = blockLocation.getHosts(); for (String host:hosts){ System.out.println(host); } } } } /** * HDFS文件和文件夹判断 * @throws IOException */ @Test public void listStatus() throws IOException { FileStatus[] listStatus = fileSystem.listStatus(new Path("/user/hadoop")); for (FileStatus fileStatus :listStatus){ if (fileStatus.isFile()){ System.out.println("f:"+fileStatus.getPath().getName()); }else { System.out.println("d:"+fileStatus.getPath().getName()); } } } @After public void after() throws IOException { fileSystem.close(); } } 将hdfs-site.xml拷贝到项目的根目录下 在src/main/resources创建hdfs-site.xml,添加: <?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet type="text/xsl" href="configuration.xsl"?> <configuration> <property> <name>dfs.replication</name> <value>1</value> </property> </configuration>

    这样副本数就改成1了

    参数优先级: 参数优先级排序:(1)客户端代码中设置的值 >(2)ClassPath下的用户自定义配置文件 >(3)然后是服务器的默认配置

    三、HDFS的I/O流操作

    上面的API操作HDFS系统都是框架封装好的。那么如果我们想自己实现上述API的操作该怎么实现呢? 我们可以采用IO流的方式实现数据的上传和下载。

    HDFS文件上传 1.1 需求:把本地d盘上的test.txt文件上传到HDFS的:/user/hadoop目录 2.1 编写代码: /** * 自定义方法上传文件 * @throws IOException */ @Test public void putFileToHDFS() throws IOException { //创建输入流 FileInputStream fileInputStream = new FileInputStream(new File("d:\\1.txt")); //获取输出流 FSDataOutputStream outputStream = fileSystem.create(new Path("/user/hadoop")); //流对拷 IOUtils.copyBytes(fileInputStream,outputStream,new Configuration()); //关闭资源 IOUtils.closeStream(fileInputStream); IOUtils.closeStream(outputStream); } HDFS文件下载 2.1 需求:从HDFS上下载banhua.txt文件到本地e盘上 2.2 编写代码 /** * 自定义HDFS文件下载 * @throws IOException */ @Test public void getFileFromHDFS() throws IOException { //获取输入流 FSDataInputStream fis = fileSystem.open(new Path("1.txt")); //获取输出流 FileOutputStream outputStream = new FileOutputStream(new File("d:\\2.txt")); //流的对拷 IOUtils.copyBytes(fis, outputStream, new Configuration()); //关闭资源 IOUtils.closeStream(fis); IOUtils.closeStream(outputStream); } 定位文件读取 3.1 需求:分块读取HDFS上的大文件,比如/user/hadoop目录下的/hadoop-2.7.2.tar.gz 3.2 编写代码 1)下载第一块 /** * 定位文件读取 * 下载第一块 * * @throws IOException */ @Test public void readFileSeek1() throws IOException { //获取输入流 FSDataInputStream fis = fileSystem.open(new Path("/user/hadoop/hadoop-2.7.2.tar.gz")); FileOutputStream fos = new FileOutputStream(new File("d:/hadoop/hadoop-2.7.2.tar.gz.part1")); byte[] buf = new byte[1024]; for (int i = 0; i < 1024 * 128; i++) { fis.read(buf); fos.write(buf); } IOUtils.closeStream(fis); IOUtils.closeStream(fos); }

    2)下载第二块

    /** * 定位文件读取 * 下载第二块 * @throws IOException */ @Test public void readFileSeek2() throws IOException { //获取输入流 FSDataInputStream fis = fileSystem.open(new Path("/user/hadoop/hadoop-2.7.2.tar.gz")); //定位输入数据位置 fis.seek(1024*1024*128); //创建输出流 FileOutputStream fos = new FileOutputStream(new File("d:/hadoop/hadoop-2.7.2.tar.gz.part2")); //流的对拷 IOUtils.copyBytes(fis,fos,new Configuration()); IOUtils.closeStream(fis); IOUtils.closeStream(fos); }

    3)合并文件 在Window命令窗口中进入到目录d:\hadoop\,然后执行如下命令,对数据进行合并 type hadoop-2.7.2.tar.gz.part2 >> hadoop-2.7.2.tar.gz.part1 合并完成后,将hadoop-2.7.2.tar.gz.part1重新命名为hadoop-2.7.2.tar.gz。解压发现该tar包非常完整。

    Processed: 0.013, SQL: 9