scala读取本地hdfs_Scala操作HDFS

本文展示了如何使用Scala进行HDFS操作,包括创建和删除目录、上传和删除文件、读取文件内容以及向文件追加内容。提供了详细的函数实现和测试代码。
摘要由CSDN通过智能技术生成

通过Scala对HDFS的一些操作,包括创建目录,删除目录,上传文件,文件读取,删除文件,Append文件等等;

import java.io._

import java.net.URI

import java.util._

import org.apache.commons.lang3.StringUtils

import org.apache.hadoop.conf.Configuration

import org.apache.hadoop.fs._

import org.apache.zookeeper.common.IOUtils

/**

* 通过scala操作HDFS

*

* @author Sunny

* @taskId:

* @version 1.0

* @createDate 2018/06/11 9:29

* @see com.spark.sunny.hdfs

*/

object HDFSUtil {

val hdfsUrl = "hdfs://iotsparkmaster:9000"

var realUrl = ""

/**

* make a new dir in the hdfs

*

* @param dir the dir may like '/tmp/testdir'

* @return boolean true-success, false-failed

*/

def mkdir(dir : String) : Boolean = {

var result = false

if (StringUtils.isNoneBlank(dir)) {

realUrl = hdfsUrl + dir

val config = new Configuration()

val fs = FileSystem.get(URI.create(realUrl), config)

if (!fs.exists(new Path(realUrl))) {

fs.mkdirs(new Path(realUrl))

}

fs.close()

result = true

}

result

}

/**

* delete a dir in the hdfs.

* if dir not exists, it will throw FileNotFoundException

*

* @param dir the dir may like '/tmp/testdir'

* @return boolean true-success, false-failed

*

*/

def deleteDir(dir : String) : Boolean = {

var result = false

if (StringUtils.isNoneBlank(dir)) {

realUrl = hdfsUrl + dir

val config = new Configuration()

val fs = FileSystem.get(URI.create(realUrl), config)

fs.delete(new Path(realUrl), true)

fs.close()

result = true

}

result

}

/**

* list files/directories/links names under a directory, not include embed

* objects

*

* @param dir a folder path may like '/tmp/testdir'

* @return List list of file names

*/

def listAll(dir : String) : List[String] = {

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值