javaapi操作hdfs详细示例(代码片段)

bitcarmanlee bitcarmanlee     2022-12-02     232

关键词:

1.遍历当前目录下所有文件与文件夹

可以使用listStatus方法实现上述需求。
listStatus方法签名如下

  /**
   * List the statuses of the files/directories in the given path if the path is
   * a directory.
   * 
   * @param f given path
   * @return the statuses of the files/directories in the given patch
   * @throws FileNotFoundException when the path does not exist;
   *         IOException see specific implementation
   */
  public abstract FileStatus[] listStatus(Path f) throws FileNotFoundException, 
                                                         IOException;

可以看出listStatus只需要传入参数Path即可,返回的是一个FileStatus的数组。
而FileStatus包含有以下信息

/** Interface that represents the client side information for a file.
 */
@InterfaceAudience.Public
@InterfaceStability.Stable
public class FileStatus implements Writable, Comparable 

  private Path path;
  private long length;
  private boolean isdir;
  private short block_replication;
  private long blocksize;
  private long modification_time;
  private long access_time;
  private FsPermission permission;
  private String owner;
  private String group;
  private Path symlink;
  ....

从FileStatus中不难看出,包含有文件路径,大小,是否是目录,block_replication, blocksize…等等各种信息。

import org.apache.hadoop.fs.FileStatus, FileSystem, Path
import org.apache.spark.sql.SparkSession
import org.apache.spark.SparkConf, SparkContext
import org.slf4j.LoggerFactory

object HdfsOperation 
	
	val logger = LoggerFactory.getLogger(this.getClass)
	
	def tree(sc: SparkContext, path: String) : Unit = 
		val fs = FileSystem.get(sc.hadoopConfiguration)
		val fsPath = new Path(path)
		val status = fs.listStatus(fsPath)
		for(filestatus:FileStatus <- status) 
			logger.error("getPermission is: ", filestatus.getPermission)
			logger.error("getOwner is: ", filestatus.getOwner)
			logger.error("getGroup is: ", filestatus.getGroup)
			logger.error("getLen is: ", filestatus.getLen)
			logger.error("getModificationTime is: ", filestatus.getModificationTime)
			logger.error("getReplication is: ", filestatus.getReplication)
			logger.error("getBlockSize is: ", filestatus.getBlockSize)
			if (filestatus.isDirectory) 
				val dirpath = filestatus.getPath.toString
				logger.error("文件夹名字为: ", dirpath)
				tree(sc, dirpath)
			 else 
				val fullname = filestatus.getPath.toString
				val filename = filestatus.getPath.getName
				logger.error("全部文件名为: ", fullname)
				logger.error("文件名为: ", filename)
			
		
	

如果判断fileStatus是文件夹,则递归调用tree方法,达到全部遍历的目的。

2.遍历所有文件

上面的方法是遍历所有文件以及文件夹。如果只想遍历文件,可以使用listFiles方法。

	def findFiles(sc: SparkContext, path: String) = 
		val fs = FileSystem.get(sc.hadoopConfiguration)
		val fsPath = new Path(path)
		val files = fs.listFiles(fsPath, true)
		while(files.hasNext) 
			val filestatus = files.next()
			val fullname = filestatus.getPath.toString
			val filename = filestatus.getPath.getName
			logger.error("全部文件名为: ", fullname)
			logger.error("文件名为: ", filename)
			logger.error("文件大小为: ", filestatus.getLen)
		
	
  /**
   * List the statuses and block locations of the files in the given path.
   * 
   * If the path is a directory, 
   *   if recursive is false, returns files in the directory;
   *   if recursive is true, return files in the subtree rooted at the path.
   * If the path is a file, return the file's status and block locations.
   * 
   * @param f is the path
   * @param recursive if the subdirectories need to be traversed recursively
   *
   * @return an iterator that traverses statuses of the files
   *
   * @throws FileNotFoundException when the path does not exist;
   *         IOException see specific implementation
   */
  public RemoteIterator<LocatedFileStatus> listFiles(
      final Path f, final boolean recursive)
  throws FileNotFoundException, IOException 
  ...

从源码可以看出,listFiles 返回一个可迭代的对象RemoteIterator<LocatedFileStatus>,而listStatus返回的是个数组。同时,listFiles返回的都是文件。

3.创建文件夹

	def mkdirToHdfs(sc: SparkContext, path: String) = 
		val fs = FileSystem.get(sc.hadoopConfiguration)
		val result = fs.mkdirs(new Path(path))
		if (result) 
			logger.error("mkdirs already success!")
		 else 
			logger.error("mkdirs had failed!")
		
	

4.删除文件夹

	def deleteOnHdfs(sc: SparkContext, path: String) = 
		val fs = FileSystem.get(sc.hadoopConfiguration)
		val result = fs.delete(new Path(path), true)
		if (result) 
			logger.error("delete already success!")
		 else 
			logger.error("delete had failed!")
		
	

5.上传文件

	def uploadToHdfs(sc: SparkContext, localPath: String, hdfsPath: String): Unit = 
		val fs = FileSystem.get(sc.hadoopConfiguration)
		fs.copyFromLocalFile(new Path(localPath), new Path(hdfsPath))
		fs.close()
	

6.下载文件

	def downloadFromHdfs(sc: SparkContext, localPath: String, hdfsPath: String) = 
		val fs = FileSystem.get(sc.hadoopConfiguration)
		fs.copyToLocalFile(new Path(hdfsPath), new Path(localPath))
		fs.close()
	

大数据hadoophdfs的javaapi操作(代码片段)

...说。好了,我们开始今天的正文。文章目录一、HDFS的JavaAPI操作二、搭建开发环境三、FileSystem实例获取讲解四、HDFS常用JavaAPI代码一、HDFS的JavaAPI操作HDFS在生产应用中主要是客户端的开发,其核心 查看详情

hdfs深入:10hdfs的javaapi操作(代码片段)

 看到10、hdfs的javaAPI操作, 13分19秒具体代码如下:/***递归遍历hdfs中所有的文件路径*/@TestpublicvoidgetAllHdfsFilePath()throwsURISyntaxException,IOException//获取fs的客户端FileSystemfileSystem=FileSystem.get(newURI("hdfs:// 查看详情

hdfs的javaapi操作(代码片段)

...文。文章目录一、HDFS的shell(命令行客户端)操作二、HDFS的javaapi操作一、HDFS的shell(命令行客户端)操作1.基本语法bin/hadoopfs具体命令或者bin/hdfsdfs具体命令2& 查看详情

hadoop3-javaapi操作hdfs(代码片段)

...用ShellCli对HDFS进行了一些基本的操作,本篇文章使用JavaApi对HDFS进行操作,下面是上篇文章地址:https://blog.csdn.net/qq_43692950/article/details/127172685如果在windows环境下使用JavaApi进行操作&# 查看详情

hadoop3-javaapi操作hdfs(代码片段)

...用ShellCli对HDFS进行了一些基本的操作,本篇文章使用JavaApi对HDFS进行操作,下面是上篇文章地址:https://blog.csdn.net/qq_43692950/article/details/127172685如果在windows环境下使用JavaApi进行操作&# 查看详情

hadoop3-javaapi操作hdfs(代码片段)

...用ShellCli对HDFS进行了一些基本的操作,本篇文章使用JavaApi对HDFS进行操作,下面是上篇文章地址:https://blog.csdn.net/qq_43692950/article/details/127172685如果在windows环境下使用JavaApi进行操作&# 查看详情

hadoop——hdfs文件系统的javaapi操作(上传下载查看删除创建文件)详细教学(代码片段)

如果还没有配置好Hadoop的可以点击链接查看如何配置各大技术基础教学、实战开发教学(正在持续更新中······)首先,启动Hadoop集群服务然后在浏览器访问Hadoop,点击Browsethefilesystem查看HDFS文件系统的目录 可... 查看详情

hdfs的javaapi详情(代码片段)

...装        <二>、配置对应的环境变量二、HDFS的JavaAPI操作     1.下载并解压Hadoop-2.4.1安装包    2.将文件hadoop.dll和文件winytils.exe放入hadoop-2.4.1解压后文 查看详情

elasticsearch7.8.0版本入门——javaapi操作(索引操作)(代码片段)

目录一、创建索引代码示例二、查询索引代码示例二、删除索引代码示例一、创建索引代码示例创建索引代码示例packagecom.xz.esdemo.day1;importorg.apache.http.HttpHost;importorg.elasticsearch.client.RequestOptions;importorg.elasticsearch.client.RestClient;impor 查看详情

elasticsearch7.8.0版本入门——javaapi操作(文档操作)(代码片段)

目录一、pom文件依赖二、创建实体对象类三、文档操作代码示例3.1、创建文档代码示例3.2、修改文档代码示例3.3、查询文档代码示例3.4、删除文档代码示例一、pom文件依赖引入相关依赖<!--elasticsearch依赖--><dependency><gro... 查看详情

大数据讲课笔记4.4使用javaapi操作hdfs(代码片段)

...习目标一、导入新课二、新课讲解(一)了解HDFSJavaAPI1、HDFS常见类与接口2、FileSystem的常用方法(二)编写Java程序访问HDFS1、创建Maven项目2、修改pom.xml文件,添加hadoop依赖3、在resources目录里创建log4j.properties... 查看详情

大数据讲课笔记4.4使用javaapi操作hdfs(代码片段)

...习目标一、导入新课二、新课讲解(一)了解HDFSJavaAPI1、HDFS常见类与接口2、FileSystem的常用方法(二)编写Java程序访问HDFS1、创建Maven项目2、修改pom.xml文件,添加hadoop依赖3、在resources目录里创建log4j.properties... 查看详情

elasticsearch7.8.0版本入门——javaapi操作(索引操作)(代码片段)

目录一、创建索引代码示例二、查询索引代码示例二、删除索引代码示例一、创建索引代码示例创建索引代码示例packagecom.xz.esdemo.day1;importorg.apache.http.HttpHost;importorg.elasticsearch.client.RequestOptions;importorg.elasticsearch.client.RestClient;impor... 查看详情

javaapi操作hdfs

...了用HDFS的shell命令对文件系统进行操作,我们也可以利用JavaAPI对文件系统进行操作,比如文件的创建、删除、修改权限等等,还有文件夹的创建、删除、重命名等等。使用JavaAPI对文件系统进行操作主要涉及以下几个类:1.Configur... 查看详情

elasticsearch7.8.0版本入门——javaapi操作(批量操作文档)(代码片段)

目录一、pom文件依赖二、批量操作文档代码示例2.1、批量创建文档代码示例2.2、批量删除文档代码示例一、pom文件依赖引入相关依赖<!--elasticsearch依赖--><dependency><groupId>org.elasticsearch</groupId><artifactId>elasticsea... 查看详情

javaapi操作hdfs

使用idea工具创建的是maven项目,操作linux环境首先需要配置好Maven环境,如果下载jar包下的慢,可以将镜像站换为阿里云的镜像【配置maven环境参考:...............(待完成)】准备工作完成即可开始编写代码1.创建maven项目  2.... 查看详情

hdfs-javaapi操作

创建一个普通的java项目导入jar包附:jar包如何来的代码阶段上传下载文件packagecom.sxuek;importorg.apache.hadoop.conf.Configuration;importorg.apache.hadoop.fs.FileSystem;im本文来自博客园,作者:jsqup,转载请注明原文链接:https://www.cnblogs.com/jsqup/p/... 查看详情

使用javaapi操作hdfs

使用javaAPI操作hdfs packagecom.zuoyan.hadoop;importjava.io.FileOutputStream;importjava.io.IOException;importjava.util.HashSet;importjava.util.Iterator;importjava.util.Map;importjava.util.Set;importor 查看详情