scala 读取txt文件的方法示例

时间:2021-05-19

文件格式分别如下

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 <- 0 until array.length){ if(i==0){ val lineArray = array(i).trim.split("\\|") lockMapList = lockMapList :+ Map("id"->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 // 从尾部遍历Array / ArrayBuffer // 使用“增强for循环”遍历Array / ArrayBuffer } def KeyFileUtil(array:Array[String]) = { var keyMapList = Map[String, String]() for (i <- 0 until array.length) { //println(array(i)) val lineArray = array(i).trim.split(",") //println(lineArray.size) if(lineArray.size==2){ keyMapList = keyMapList ++ Map(lineArray(0).trim -> 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) }}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章