package com.bill.www
/**
* Created by Bill on 2016/2/3.
* 目的:用scala实现简单的数据计算
* 源文件:接口记录条数20条,包括时间戳和浮点型数据
* 执行方式:scala ReadFile.scala "E:\\spark\\data\\i_22_221000000073_L_20151016\\i_22_221000000073_L_20151016_223458.dat"
* 开发环境:win10 + IJ IDEA15.0.2 + scala2.11.7 + java1.7
*/
import scala.collection.mutable
import scala.io.Source
object ReadFile {
def main(args: Array[String]) {
println("hello-------------------------------------------------------")
// 读取文件并逐行打印其内容和长度
if(args.length > 0) {
for( line <- Source.fromFile(args(0)).getLines)
print(line.length + "\t-- " +line + "\n")
}
else
Console.err.println("Please enter a file or file with directory")
println("--------------------------------------------------------1st.")
// 用ArrayBuffer来存一列数据,通过对对象的一些操作来实现各种计算
val nums = mutable.ArrayBuffer[Float]()
if(args.length > 0) {
for( line <- Source.fromFile(args(0)).getLines) {
// 逐行处理
// 拆分字段,类型转换,追加到可变数组
nums += line.split(" ")(1).toFloat
}
}
else
Console.err.println("Please enter a file or file with directory")
// 做一些简单的计算,并输出计算结果
// common calculate
println(nums.sum)
println(nums.length)
println(nums.max)
println(nums.min)
// average
println(nums.sum/nums.length)
println("--------------------------------------------------------2nd.")
// sort desc
nums.sorted.reverse foreach(println)
println("--------------------------------------------------------end.")
}
}
hello-------------------------------------------------------
21 -- 22:34:58.0000 23.9299
20 -- 22:34:58.0005 23.927
21 -- 22:34:58.0010 23.9277
21 -- 22:34:58.0015 23.9284
20 -- 22:34:58.0020 23.927
21 -- 22:34:58.0025 23.9256
20 -- 22:34:58.0030 23.927
20 -- 22:34:58.0035 23.927
21 -- 22:34:58.0040 23.9263
21 -- 22:34:58.0045 23.9284
21 -- 22:34:58.0050 23.9277
21 -- 22:34:58.0055 23.9263
21 -- 22:34:58.0060 23.9291
21 -- 22:34:58.0065 23.9256
21 -- 22:34:58.0070 23.9277
21 -- 22:34:58.0075 23.9256
21 -- 22:34:58.0080 23.9241
21 -- 22:34:58.0085 23.9263
20 -- 22:34:58.0090 23.927
21 -- 22:34:58.0095 23.9263
--------------------------------------------------------1st.
478.54
20
23.9299
23.9241
23.927
--------------------------------------------------------2nd.
23.9299
23.9291
23.9284
23.9284
23.9277
23.9277
23.9277
23.927
23.927
23.927
23.927
23.927
23.9263
23.9263
23.9263
23.9263
23.9256
23.9256
23.9256
23.9241
--------------------------------------------------------end.