liudehaos

还历史以真诚,还生命以过程。 ——余秋雨
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Scala(二)IO流 读取文件和保存文件

Posted on 2022-07-20 20:27  liudehaos  阅读(351)  评论(0编辑  收藏  举报
package com.shujia.scala

import java.io.{BufferedReader, FileReader, FileWriter}
import scala.io.{BufferedSource, Source}

object Demo2IO {
  def main(args: Array[String]): Unit = {
    /*
    读取文件
    1、java中的方法
    2、Scala中source方法
     */
    val reader = new BufferedReader(new FileReader("data/demotxt.txt"))
    var line: String = reader.readLine()
    while (line != null) {
      //打印这一行的信息
      println(line)
      //每次循环读取下一行
      line = reader.readLine()
    }
    reader.close()
    print("====" * 20 + "\n")

    val bufferedSource: BufferedSource = Source.fromFile("data/demotxt.txt")
    val iterator: Iterator[String] = bufferedSource.getLines()
    for (elem <- iterator) {
      println(elem)
    }
    bufferedSource.close()

    /**/
    val writer = new FileWriter("data/out1.txt")
    writer.write("java")
    writer.write("\t")
    writer.write("hadoop")
    writer.write("\t")
    writer.write("spark")
    writer.write("\t")
    writer.write("flink")
    writer.write("\t")
    writer.write("python")
    writer.write("\t")
    writer.write("hive")
   writer.close()
  }
}
package shujia

import java.io.{BufferedReader, FileReader, FileWriter}
import scala.io.{BufferedSource, Source}

object Demo2IO {
  def main(args: Array[String]): Unit = {
    /*
    读取文件
    1、java中的方法
    2、Scala中source方法
     */
    val reader = new BufferedReader(new FileReader("data/demotxt.txt"))
    var line: String = reader.readLine()
    while (line != null) {
      //打印这一行的信息
      println(line)
      //每次循环读取下一行
      line = reader.readLine()
    }
    reader.close()
    print("====" * 20 + "\n")

    val bufferedSource: BufferedSource = Source.fromFile("data/demotxt.txt")
    val iterator: Iterator[String] = bufferedSource.getLines()
    for (elem <- iterator) {
      println(elem)
    }
    bufferedSource.close()

    /**/
    val writer = new FileWriter("data/out1.txt")
    writer.write("java")
    writer.write("\t")
    writer.write("hadoop")
    writer.write("\t")
    writer.write("spark")
    writer.write("\t")
    writer.write("flink")
    writer.write("\t")
    writer.write("python")
    writer.write("\t")
    writer.write("hive")
   writer.close()
  }
}