欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

scala 读取txt文件的方法示例

程序员文章站 2024-02-13 17:23:16
文件格式分别如下     package txt object readtxt { def readfrom...

文件格式分别如下

 scala 读取txt文件的方法示例  

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)
 
 
 }
}

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