1.作业:统计目录下面的文件所有单词
2.代码实现
package
com.jn.scala.wangjialin.copy
import java.io.File
import scala.io.Source
/**
* Created by admin on 2016/1/9.
*/
object WordCounter {
//存储单词和个数
var map = Map . empty[ String , Int]
def main(args: Array[ String ]) {
val files2 = subFileNames( new File( "d:/test" ))
for (i <- files2){
readFile(i)
println(i)
}
map .foreach(f =>println(f))
}
/**
* 递归调用获取所有文件的全路径
* @param dir
* @return
*/
def subFileNames(dir: File): Iterator [File]={
val d = dir.listFiles.filter(_.isDirectory)
val f = dir.listFiles.filter(_.isFile).toIterator
f ++ d.toIterator.flatMap(subFileNames(_))
}
/**
* 获取文件的每一个行
* @param file
*/
def readFile(file: File){
val f = Source.fromFile(file)
for (line <- f.getLines()){
count(line)
}
}
/**
* 进行计算
* @param line
*/
def count(line: String ) = {
for (word <- line.split( " " )){
if ( map .contains(word))
map += (word -> ( map (word)+ 1 ))
else
map += (word -> 1 )
}
}
}