Scala(二)IO流 读取文件和保存文件
作者:互联网
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() } }
标签:文件,String,val,Scala,IO,reader,line,读取 来源: https://www.cnblogs.com/liudehaos/p/16499740.html