我正在尝试使用Scala获取所有目录的列表以及计算机上所有文件的列表。以下是我尝试解决问题的两种不同方式。为什么我得到空指针异常?
def fullDirList(directories: Array[String]): Array[String ] = {
directories.foldLeft( Array[String]() ){ (x, y) => x ++: fullDirList(getSubDirList(y))
}
def getFullDirList(directories: Array[String]): Array[String] = {
def loop(dir: Array[String], accDir: Array[String]): Array[String] = {
if (dir.isEmpty) accDir
else loop( dir.tail, accDir ++: getFullDirList( getSubDirList( dir.head ) ) )
} // END loop()
loop(directories, Array[String]())
} // END getFullDirList()
def getSubDirList(directoryName: String): Array[String] = {
( new File(directoryName) ).listFiles.filter(_.isDirectory).map(_.getName )
}
def getFileArray(directoryName: String): Array[String] = {
( new File(directoryName) ).listFiles.filter(_.isFile).map(_.getAbsolutePath)
}
答案 0 :(得分:0)
这是我最终提出的解决方案。虽然我确定你可以用foldRight做到这一点,但我很高兴解决方案有效。
def getDirList(directoryName: String): Array[String] = {
( new File(directoryName) ).listFiles.filter(_.isDirectory).map(_.getAbsolutePath)
}
def getAllDirs(dir: String): Array[String] = {
val dirList = getDirList(dir)
def loop(directories: Array[String], accList: Array[String]): Array[String] = {
if(directories.isEmpty) accList
else loop(directories.tail, accList ++: getDirList(directories.head))
}
loop(dirList, Array[String]())
}