在scala中从hdfs返回路径

gv8xihay  于 2021-05-29  发布在  Hadoop
关注(0)|答案(1)|浏览(308)

我想返回的路径文件,我给一个文件夹,并在该文件夹中搜索“部分”文件。

def listDirectoriesGetPartFile(folderPath: String): org.apache.hadoop.fs.Path  {

val path = new Path(folderPath)
 if (fileSystem.isDirectory(path)) {
  val st = fileSystem.listStatus(path)
  for (i <- 0 until st.length) {
    if (st(i).getPath.getName.toString().trim().contains("part")) {
      st(i).getPath
    }
  }

 }
 ????
}

我想退票 part- 文件。
我怎样才能做到呢?

k97glaaz

k97glaaz1#

这里有几个选项(按照scala习惯用法的升序排列)。我想你是想把这个还给我 null (尽管强烈建议不要)如果找不到匹配的文件:
使用可变变量:

def listDirectoriesGetPartFile(folderPath: String): Path = {
  val path = new Path(folderPath)
  var result: Path = null // use a var with a default value
  if (fileSystem.isDirectory(path)) {
    val st = fileSystem.listStatus(path)
    // update the value of result if we found what we're looking for
    result = st.map(_.getPath).find(_.getName.trim.contains("part")).orNull
  }
  result // return the var
}

在scala中使用if-else,一切都是一个表达式,因此if-else表达式可以是返回值:

def listDirectoriesGetPartFile(folderPath: String): Path = {
  val path = new Path(folderPath)
  if (fileSystem.isDirectory(path)) {
    val st = fileSystem.listStatus(path)
    st.map(_.getPath).find(_.getName.trim.contains("part")).orNull
  } else {
    null
  }
}

更改签名以返回一个选项:由于此方法可能会找到您要查找的路径,但可能不会找到(如果给定的路径不是文件夹,或者如果文件夹中不存在这样的文件),因此最好使用返回类型来传递这种可能性—这就是scala的作用所在 Option 可以使用。为了方便起见,我还将使用模式匹配替换if-else,但这不是必须的:

def listDirectoriesGetPartFile(folderPath: String): Option[Path] = {
  new Path(folderPath) match {
    case p if fileSystem.isDirectory(p) => fileSystem.listStatus(p)
      .map(_.getPath)
      .find(_.getName.trim.contains("part"))
    case _ => None
  }
}

相关问题