scala学习笔记之文件IO操作

Scala 进行文件写操作,直接用的都是 java中 的 I/O 类 (java.io.File):

1.读取本地磁盘

var source = Source.fromFile("D:\\test.txt","GB2312")
    var lines = source.getLines;     //获得迭代器
    for(line <- lines) println(line)

    var sourceArr = source.getLines().toArray        //读取成一个数组
    var sourceBuffer = source.getLines().toBuffer    //读取成一个缓冲
    val str = source.mkString;          //小文件读取成一个字符串
    for(c <- source){println(c)}      //逐个字符读取

    source.getLines().foreach { line => println(line) }  //scala的写法

    source.close()                    //用完之后需要进行关闭操作

2.从字符串读取

 val sourceFromString = Source.fromString("hello this is scala note")
    println(sourceFromString.mkString("<","-",">"))
    sourceFromString.close()

3.从URL读取,并写入本地磁盘

  val sourceFromUrl = Source.fromURL("http://www.baidu.com","utf-8")
    val urlLines = sourceFromUrl.getLines();
    var print = new PrintWriter("d:\\baidu.html");
    for(line <- urlLines){
      print.println(line)
      print.flush()
    }
    print.close()
    sourceFromUrl.close()





4.读取控制台的输入

  println("how old are you")
    var age = scala.io.StdIn.readInt()       
    var readLine = scala.io.StdIn.readLine() 
    println("your age is "+age)

5.读取二进制文件:scala不能直接读取和写入二进制文件,需要借助于JAVA来进行读取,这种方式还是按照java方式来去写scala,后期scala熟练后再进行更改

 def readAndWriteBinaryFile: Unit = {
        var file = new File("D:\\mycat.wmv")
        val bis = new BufferedInputStream(new FileInputStream(file))
        var byte = new Array[Byte](4096)
        var len = 0
        var outFile = new File("d:\\mycat_copy.wmv")
        var bos = new BufferedOutputStream(new FileOutputStream(outFile))
        while ({ len = bis.read(byte); len != -1 }) { //一定要这么写
            /*
             *  while((len = bis.read(byte)) != -1){   
             * 这么写会出现comparing values of types Unit and Int using `!=' 
             * will always yield true ,并在len = -1出现异常
             */
            bos.write(byte, 0, len);
            bos.flush();
        }
        bos.close()
        bis.close()

  }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值