您好,登錄后才能下訂單哦!
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文件問題的解答就分享到這里了,希望以上內容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注億速云行業資訊頻道了解更多相關知識。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。