您好,登錄后才能下訂單哦!
這篇文章給大家介紹使用scala如何讀取txt文件,內(nèi)容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
文件格式分別如下
package txt object ReadTxt { def readFromTxtByLine(filePath:String) = { //導入Scala的IO包 import scala.io.Source //以指定的UTF-8字符集讀取文件,第一個參數(shù)可以是字符串或者是java.io.File val source = Source.fromFile(filePath, "UTF-8") //或取文件中所有行 //val lineIterator = source.getLines() //迭代打印所有行 //lineIterator.foreach() //將所有行放到數(shù)組中 val lines = source.getLines().toArray source.close() //println(lines.size) lines } def LackingFileUtil(array:Array[String],keyMap:Map[String,String]) = { // 使用for循環(huán)和until遍歷Array / ArrayBuffer // 使until是RichInt提供的函數(shù) 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循環(huán)”遍歷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文件就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。