Scala学习笔记(三):从文件里读取文本行

第一版

test-scala.sh文件内容如下:

#!/bin/sh
exec scala "$0" "$@"
!#

println("Hello, Welcome to https://www.iteblog.com!")

args.foreach(println)

import scala.io.Source
if(args.length>0){
  for(line<-Source.fromFile(args(0)).getLines)
    println(line.length+" "+line)
}else{
  Console.err.println("Please enter FileName")
}

运行上述代码(命令:sh test-scala.sh test-scala.sh),输出形式如下:

 

 

从上图可以看出,行首的字符数影响了代码排版

 

第二版 - 固定行首字符数所占的宽度

预期得到如下效果图:

 

 

思路:

1)定义widthOfLength方法用于计算行宽

2)找到最长的一行

3)将该行字符串传给widthOfLength,得到最大宽度

import scala.io.Source
def widthOfLength(s:String)=s.length.toString.length
if(args.length>0){
  val lines=Source.fromFile(args(0)).getLines.toList
  var maxWidth=0
  for(line<-lines)
    maxWidth=maxWidth.max(widthOfLength(line))
  for(line<-lines){
    val numSpaces=maxWidth-widthOfLength(line)
    val padding=" "*numSpaces
    println(padding+line.length+"|"+line)
  }
}else{
  Console.err.println("Please enter FileName")
}

 

第三版

Scale属于 OOP 与 FP 混合的编程语言,在函数式编程中不推荐使用var

import scala.io.Source
def widthOfLength(s:String)=s.length.toString.length
if(args.length>0){
  val lines=Source.fromFile(args(0)).getLines.toList
  val longestLine=lines.reduceLeft(
    (a,b)=>if(a.length>b.length) a else b
  )
  val maxWidth=widthOfLength(longestLine)
  for(line<-lines){
    val numSpaces=maxWidth-widthOfLength(line)
    val padding=" "*numSpaces
    println(padding+line.length+"|"+line)
  }
}else{
  Console.err.println("Please enter FileName")
}

 

 
posted @ 2015-08-15 18:02  时空穿越者  阅读(9509)  评论(0编辑  收藏  举报