Scala-文件操作

1、读取文件

import scala.io.Source

object Model {

  def main(args: Array[String]): Unit = {

    val  s = Source.fromFile("d:/hello.txt");
    val  lines = s.getLines();
    for (line<-lines){
      print(line+"
");
    }
  }


}

2、按照空格符分隔

import scala.io.Source

object Model {

  def main(args: Array[String]): Unit = {

    val  s = Source.fromFile("d:/hello.txt").mkString;
    /*
    s 空白符
    S 非空白符
    [sS]任意字符*/

    val str =  s.split("\s+");//按照空白符分隔,也就是空格
    for (s1 <- str){
    println(s1);
    }
  }


}

3、爬取网页图片

import java.io.FileOutputStream
import java.net.URL

object CrawlerDemo {

  def main(args: Array[String]): Unit = {
    //获取到需要爬取的网页的地址
    val url = new URL("https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=3282064063,1617178826&fm=27&gp=0.jpg");

    //输入流
    val in =  url.openStream();

    //输出流
    val out =  new FileOutputStream("d:/4.jpg");

    //长度
    var len = 0;

    //缓冲区
    val buf = new Array[Byte](1048576);

    //开始读取
    in.read(buf);
    //写入缓冲区
    out.write(buf);

    //关闭输出输入流
    out.close();
    in.close();



  }

}
欢迎关注我的公众号:小秋的博客 CSDN博客:https://blog.csdn.net/xiaoqiu_cr github:https://github.com/crr121 联系邮箱:rongchen633@gmail.com 有什么问题可以给我留言噢~
原文地址:https://www.cnblogs.com/flyingcr/p/10327101.html