Scala操作HDFS

通過(guò)Scala對(duì)HDFS的一些操作柬姚,包括創(chuàng)建目錄拟杉,刪除目錄,上傳文件量承,文件讀取,刪除文件,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

/**
  * <Description> 通過(guò)scala操作HDFS<br>
  *
  * @author Sunny<br>
  * @taskId: <br>
  * @version 1.0<br>
  * @createDate 2018/06/11 9:29 <br>
  * @see com.spark.sunny.hdfs <br>
  */
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<String> list of file names
    */
  def listAll(dir : String) : List[String] = {
    val names : List[String] = new ArrayList[String]()
    if (StringUtils.isNoneBlank(dir)) {
      realUrl = hdfsUrl + dir
      val config = new Configuration()
      val fs = FileSystem.get(URI.create(realUrl), config)
      val stats = fs.listStatus(new Path(realUrl))
      for (i <- 0 to stats.length - 1) {
        if (stats(i).isFile) {
          names.add(stats(i).getPath.toString)
        } else if (stats(i).isDirectory) {
          names.add(stats(i).getPath.toString)
        } else if (stats(i).isSymlink) {
          names.add(stats(i).getPath.toString)
        }
      }
    }
    names
  }

  /**
     * upload the local file to the hds,
     * notice that the path is full like /tmp/test.txt
     * if local file not exists, it will throw a FileNotFoundException
     *
     * @param localFile local file path, may like F:/test.txt or /usr/local/test.txt
     *
     * @param hdfsFile hdfs file path, may like /tmp/dir
     * @return boolean true-success, false-failed
     *
     **/
  def uploadLocalFile2HDFS(localFile : String, hdfsFile : String) : Boolean = {
    var result = false
    if (StringUtils.isNoneBlank(localFile) && StringUtils.isNoneBlank(hdfsFile)) {
      realUrl = hdfsUrl + hdfsFile
      val config = new Configuration()
      val hdfs = FileSystem.get(URI.create(hdfsUrl), config)
      val src = new Path(localFile)
      val dst = new Path(realUrl)
      hdfs.copyFromLocalFile(src, dst)
      hdfs.close()
      result = true
    }
     result
  }

  /**
    * create a new file in the hdfs. notice that the toCreateFilePath is the full path
    *  and write the content to the hdfs file.

    * create a new file in the hdfs.
    * if dir not exists, it will create one
    *
    * @param newFile new file path, a full path name, may like '/tmp/test.txt'
    * @param content file content
    * @return boolean true-success, false-failed
    **/
  def createNewHDFSFile(newFile : String, content : String) : Boolean = {
    var result = false
    if (StringUtils.isNoneBlank(newFile) && null != content) {
      realUrl = hdfsUrl + newFile
      val config = new Configuration()
      val hdfs = FileSystem.get(URI.create(realUrl), config)
      val os = hdfs.create(new Path(realUrl))
      os.write(content.getBytes("UTF-8"))
      os.close()
      hdfs.close()
      result = true
    }
    result
  }

  /**
    * delete the hdfs file
    *
    * @param hdfsFile a full path name, may like '/tmp/test.txt'
    * @return boolean true-success, false-failed
    */
  def deleteHDFSFile(hdfsFile : String) : Boolean = {
    var result = false
    if (StringUtils.isNoneBlank(hdfsFile)) {
      realUrl = hdfsUrl + hdfsFile
      val config = new Configuration()
      val hdfs = FileSystem.get(URI.create(realUrl), config)
      val path = new Path(realUrl)
      val isDeleted = hdfs.delete(path, true)
      hdfs.close()
      result = isDeleted
    }
    result
  }

  /**
    * read the hdfs file content
    *
    * @param hdfsFile a full path name, may like '/tmp/test.txt'
    * @return byte[] file content
    */
  def readHDFSFile(hdfsFile : String) : Array[Byte] = {
    var result =  new Array[Byte](0)
    if (StringUtils.isNoneBlank(hdfsFile)) {
      realUrl = hdfsUrl + hdfsFile
      val config = new Configuration()
      val hdfs = FileSystem.get(URI.create(realUrl), config)
      val path = new Path(realUrl)
      if (hdfs.exists(path)) {
        val inputStream = hdfs.open(path)
        val stat = hdfs.getFileStatus(path)
        val length = stat.getLen.toInt
        val buffer = new Array[Byte](length)
        inputStream.readFully(buffer)
        inputStream.close()
        hdfs.close()
        result = buffer
      }
    }
    result
  }

  /**
    * append something to file dst
    *
    * @param hdfsFile a full path name, may like '/tmp/test.txt'
    * @param content string
    * @return boolean true-success, false-failed
    */
  def append(hdfsFile : String, content : String) : Boolean = {
    var result = false
    if (StringUtils.isNoneBlank(hdfsFile) && null != content) {
      realUrl = hdfsUrl + hdfsFile
      val config = new Configuration()
      config.set("dfs.client.block.write.replace-datanode-on-failure.policy", "NEVER")
      config.set("dfs.client.block.write.replace-datanode-on-failure.enable", "true")
      val hdfs = FileSystem.get(URI.create(realUrl), config)
      val path = new Path(realUrl)
      if (hdfs.exists(path)) {
        val inputStream = new ByteArrayInputStream(content.getBytes())
        val outputStream = hdfs.append(path)
        IOUtils.copyBytes(inputStream, outputStream, 4096, true)
        outputStream.close()
        inputStream.close()
        hdfs.close()
        result = true
      }
    } else {
      HDFSUtil.createNewHDFSFile(hdfsFile, content);
      result = true
    }
    result
  }

}

測(cè)試代碼如下:

/**
  * <Description> <br>
  *
  * @author Sunny<br>
  * @taskId: <br>
  * @version 1.0<br>
  * @createDate 2018/06/11 13:16 <br>
  * @see com.spark.sunny.hdfs <br>
  */
object TestHDFSUtil {
  val dir = "/iotcmp/cdr"
  val parentDir = "/iotcmp"
  val hdfsUrl = "hdfs://iotsparkmaster:9000"
  def main(args: Array[String]): Unit = {
    //testDeletedirNormal
    //testUploadLocalFile2HDFS
    //testCreateNewHDFSFileNormal
    testDeleteHDFSFile
    //testReadHDFSFile
    //testAppend
  }

  @Test
  def testMkdirNull(): Unit = {
    try{
      assertEquals(false, HDFSUtil.mkdir(null));
      assertEquals(false, HDFSUtil.mkdir(" "));
      assertEquals(false, HDFSUtil.mkdir(""));
    } catch {
      case ex : Exception => assertEquals(true, false);
    }
  }

  def testMkdirNormal(): Unit = {
    HDFSUtil.deleteDir(dir)
    var result : Boolean = HDFSUtil.mkdir(dir)
    val listFile: List[String] = HDFSUtil.listAll(parentDir)
    var existFile = false
    for (i <- 0 to listFile.size() - 1) {
      val elem = listFile.get(i)
      if(elem.equals(hdfsUrl + dir)) {
        existFile = true
      }
    }
    println(existFile)
  }

  @Test
  def testDeletedirNull(): Unit = {
    try{
      assertEquals(false, HDFSUtil.deleteDir(null));
      assertEquals(false, HDFSUtil.deleteDir(" "));
      assertEquals(false, HDFSUtil.deleteDir(""));
    } catch {
      case ex : Exception => assertEquals(true, false);
    }
  }

  def testDeletedirNormal(): Unit = {
    HDFSUtil.deleteDir(dir)
    val listFile: List[String] = HDFSUtil.listAll(parentDir)
    var existFile = false
    for (i <- 0 to listFile.size() - 1) {
      val elem = listFile.get(i)
      if(elem.equals(hdfsUrl + dir)) {
        existFile = true
      }
    }
    println(existFile)
  }

  def testUploadLocalFile2HDFS(): Unit = {
    val localFile = "C:\\Users\\yaj\\Desktop\\CDR\\USAGE_CDR_53_888_0.cdr"
    val remoteFile = dir + "/USAGE_CDR_53_888_0.cdr"
    HDFSUtil.mkdir(dir)
    HDFSUtil.deleteHDFSFile(remoteFile)
    HDFSUtil.uploadLocalFile2HDFS(localFile, remoteFile)
  }

  def testCreateNewHDFSFileNormal(): Unit = {
    val newFile = dir + "/iot.txt"
    val content = "iot file1"
    HDFSUtil.deleteHDFSFile(newFile)
    HDFSUtil.createNewHDFSFile(newFile, content)
    val result = new String(HDFSUtil.readHDFSFile(newFile))
    println(result)
  }

  def testDeleteHDFSFile(): Unit = {
    this.testCreateNewHDFSFileNormal()
    val remoteFile = dir + "/iot.txt"
    val isDeleted : Boolean = HDFSUtil.deleteHDFSFile(remoteFile)
    println(isDeleted)
  }

  def testReadHDFSFile(): Unit = {
    //this.testUploadLocalFile2HDFS()
    val remoteFile = dir + "/USAGE_CDR_53_888_0.cdr"
    val result = new String(HDFSUtil.readHDFSFile(remoteFile))
    println("USAGE_CDR_53_888_0.cdr: " + result)
  }

  def testAppend(): Unit = {
    val newFile = dir + "/iot.txt"
    val content1 = "hello iot append1 \r\n"
    val content2 = "hello iot append2 \r\n"

    HDFSUtil.deleteHDFSFile(newFile)
    HDFSUtil.createNewHDFSFile(newFile, content1)
    HDFSUtil.append(newFile, content2)
    val result = new String(HDFSUtil.readHDFSFile(newFile))
    println(result)
  }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末削彬,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子忧风,更是在濱河造成了極大的恐慌默色,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,919評(píng)論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件阀蒂,死亡現(xiàn)場(chǎng)離奇詭異该窗,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)蚤霞,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,567評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門酗失,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人昧绣,你說(shuō)我怎么就攤上這事规肴。” “怎么了夜畴?”我有些...
    開(kāi)封第一講書人閱讀 163,316評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵拖刃,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我贪绘,道長(zhǎng)兑牡,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書人閱讀 58,294評(píng)論 1 292
  • 正文 為了忘掉前任税灌,我火速辦了婚禮均函,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘菱涤。我一直安慰自己苞也,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,318評(píng)論 6 390
  • 文/花漫 我一把揭開(kāi)白布粘秆。 她就那樣靜靜地躺著如迟,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上此再,一...
    開(kāi)封第一講書人閱讀 51,245評(píng)論 1 299
  • 那天劳吠,我揣著相機(jī)與錄音,去河邊找鬼痒玩。 笑死,一個(gè)胖子當(dāng)著我的面吹牛奴曙,可吹牛的內(nèi)容都是我干的草讶。 我是一名探鬼主播,決...
    沈念sama閱讀 40,120評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼坤溃,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼嘱丢!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起越驻,我...
    開(kāi)封第一講書人閱讀 38,964評(píng)論 0 275
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤缀旁,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后并巍,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,376評(píng)論 1 313
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡嘶窄,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,592評(píng)論 2 333
  • 正文 我和宋清朗相戀三年距贷,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了吻谋。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,764評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡阁最,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出速种,到底是詐尸還是另有隱情,我是刑警寧澤馏颂,帶...
    沈念sama閱讀 35,460評(píng)論 5 344
  • 正文 年R本政府宣布棋傍,位于F島的核電站,受9級(jí)特大地震影響瘫拣,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜派昧,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,070評(píng)論 3 327
  • 文/蒙蒙 一拢切、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧岖是,春花似錦、人聲如沸豺撑。這莊子的主人今日做“春日...
    開(kāi)封第一講書人閱讀 31,697評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)陆错。三九已至金赦,卻和暖如春音瓷,著一層夾襖步出監(jiān)牢的瞬間夹抗,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書人閱讀 32,846評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工杏愤, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人通殃。 一個(gè)月前我還...
    沈念sama閱讀 47,819評(píng)論 2 370
  • 正文 我出身青樓厕宗,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親媳瞪。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,665評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容