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 <- 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 /*for(i <- 0 until (array.length, 2)) println(array(i))*/ // 从尾部遍历Array / ArrayBuffer /*for(i <- (0 until array.length).reverse) println(array(i))*/ // 使用“增强for循环”遍历Array / ArrayBuffer /*for (e <- array){ println(e) e.split(",").mkString }*/ } 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) }}
关于scala中怎么读取txt文件问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注创新互联行业资讯频道了解更多相关知识。