Scala文件IO –写入文件,读取文件
时间:2020-02-23 14:41:46 来源:igfitidea点击:
今天,我们将研究Scala File IO操作。
文件操作主要包括从文件读取数据或者将数据写入文件。
其中我们将研究Scala读取文件和Scala写入文件程序。
Scala文件IO
Scala读取文件
我们可以使用scala.io.Source从文件中读取数据。
为了读取文件,我们创建了一个包含以下内容的测试文件。
data.txt
theitroad is a great platform for Java Developers. theitroad is online log of hyman Kumar.
这是一个简单的程序,其中我们使用Scala Source类将文件数据读取为String,然后使用正则表达式将其拆分为Map。
最后,我们在文件内容中打印theitroad的计数。
Wordcount.scala
import scala.io.Source object Wordcount { def main(args:Array[String]) { println(Source.fromFile("data.txt")) //returns scala.io.BufferedSource non-empty iterator instance val s1 = Source.fromFile("data.txt").mkString; //returns the file data as String println(s1) //splitting String data with white space and calculating the number of occurrence of each word in the file val counts = s1.split("\s+").groupBy(x=>x).mapValues(x=>x.length) println(counts) println("Count of theitroad word:"+counts("theitroad")) } }
下图显示了Scala读取文件程序的执行和输出。
逐行单词计数:有时需要处理每一行而不是文件的全部内容。
这可以通过getLines
方法来实现。
例如下面的代码;
println(Source.fromFile("data.txt").getLines()) Source.fromFile("data.txt").getLines.foreach { x => println(x) };
将产生以下输出;
non-empty iterator theitroad is a great platform for Java Developers. theitroad is online log of hyman Kumar.
现在让我们看看如何提取特定的行集。
Source.fromFile("data.txt").getLines.take(1).foreach { x => println(x) }; Source.fromFile("data.txt").getLines.slice(0, 1).foreach { x => println(x) };
" take(n)"方法用于选择迭代器的前n个值,其中" slice(from,until)"返回迭代器的一部分,其中" from"索引是slice的一部分,而" until"索引不是。
因此,以上代码片段中的两行都在做相同的事情。
Scala写入文件
Scala标准库不包含任何用于写入文件的类,因此我们将使用Java IO类将Scala写入文件。
下面是一个简单的程序,显示了如何在Scala中写入文件。
写.scala
import java.io.File import java.io.PrintWriter import scala.io.Source object Write { def main(args: Array[String]) { val writer = new PrintWriter(new File("Write.txt")) writer.write("Hello Developer, Welcome to Scala Programming.") writer.close() Source.fromFile("Write.txt").foreach { x => print(x) } } }
这将产生具有给定内容的文件Write.txt,然后Source将读取并打印相同的文件数据。