码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-08-15 19:42:07      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:

第一个版本:

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

 

 

运行该程序时抛出了异常:java.lang.OutOfMemoryError:Java heap space

是因为文件过大?

错误原因暂时不管,可以参考文章:http://www.cnblogs.com/cyjch/archive/2012/04/10/2440421.html

 

第二版:

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
    print(padding+line.length+"|"+line)
  }
}else{
  Console.err.println("Please enter FileName")
}

 

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

标签:

原文地址:http://www.cnblogs.com/studyLog-share/p/4732875.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!