微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

scala 读取txt文件的方法示例

这篇文章主要介绍了scala 读取txt文件方法示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

文件格式分别如下

 

  

package txt object ReadTxt { def readFromTxtByLine(filePath:String) = { //导入Scala的IO包 import scala.io.source //以指定的UTF-8字符集读取文件,第一个参数可以是字符串或者是java.io.File val source = Source.fromFile(filePath, "UTF-8") //或取文件中所有行 //val lineIterator = source.getLines() //迭代打印所有行 //lineIterator.foreach() //将所有行放到数组中 val lines = source.getLines().toArray source.close() //println(lines.size) lines } def LackingFileUtil(array:Array[String],keyMap:Map[String,String]) = { // 使用for循环和until遍历Array / ArrayBuffer // 使until是RichInt提供的函数 var lockMapList = List[Map[String,String]]() for (i lineArray(0).trim,"name"->lineArray(1).trim,"pass"->lineArray(2).trim) }else{ val lineArray = array(i).split(",") if(lineArray.length==3){ lockMapList = lockMapList :+ Map("id"->lineArray(0).trim,"name"->lineArray(1).trim,"pass"->lineArray(2).trim) }else if(lineArray.length==2){ val pass = keyMap.getorElse(lineArray(0).trim,lineArray(1).trim) lockMapList = lockMapList :+ Map("id"->lineArray(0).trim,"name"->lineArray(1).trim,"pass"->pass.trim) }else if(lineArray.length==1){ lockMapList = lockMapList :+ Map("id"->lineArray(0).trim,"name"->"","pass"->"") }else{ lockMapList = lockMapList :+ Map("id"->"-","name"->"","pass"->"") } } //println(array(i)) } lockMapList // 跳跃遍历Array / ArrayBuffer /*for(i lineArray(1).trim) }else if(lineArray.size==1){ keyMapList = keyMapList ++ Map(lineArray(0).trim -> "") }else{ keyMapList = keyMapList ++ Map("-" -> "") } } keyMapList } def isEmpty(s: String): Boolean = (s == null) || (s.size==0) }

package txt import scala.reflect.io.File object App { def main(args: Array[String]): Unit = { val key = ReadTxt.readFromTxtByLine("D:"+File.separator+"workspace"+File.separator+"source.txt") //println(key.mkString) val keyMap = ReadTxt.KeyFileUtil(key) //println(keyMap) val lack = ReadTxt.readFromTxtByLine("D:"+File.separator+"workspace"+File.separator+"source1.txt") val lockMapList = ReadTxt.LackingFileUtil(lack,keyMap) println(lockMapList) } }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐