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 = Lines()
//迭代打印所有⾏
//lineIterator.foreach()
//将所有⾏放到数组中
val lines = Lines().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 = OrElse(lineArray(0).trim,lineArray(1).trim)
lockMapList = lockMapList :+ Map("id"->lineArray(0).trim,"name"->lineArray(1).trim,"pass"-&im)
}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{
spring怎么读文件keyMapList = keyMapList ++ Map("-" -> "")
}
}
keyMapList
}
def isEmpty(s: String): Boolean = (s == null) || (s.size==0)
}
package txt
flect.io.File
object App {
def main(args: Array[String]): Unit = {
val key = adFromTxtByLine("D:"+File.separator+"workspace"+File.separator+"") //println(key.mkString)
val keyMap = ReadTxt.KeyFileUtil(key)
//println(keyMap)
val lack = adFromTxtByLine("D:"+File.separator+"workspace"+File.separator+"") val lockMapList = ReadTxt.LackingFileUtil(lack,keyMap)
println(lockMapList)
}
}
以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。