Implementation of File Operation and Network Request in Scala


1. Read data for each line in the file

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

// pay attention to the encoding format of the file. If the encoding format is not correct, read the wrong report. 

val file: BufferedSource = Source.fromFile("F:\files\file.txt","GBK"); 

 val lines: Iterator[String] = file.getLines() 

for(line <- lines){ 



// Pay attention to closing files 



If you want to convert the file content to an array, call toArray directly.

2. Reading Lexical Units and Numbers

If you want to read characters in groups separated by a character or a regular expression, you can do this:

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

 val file: BufferedSource = Source.fromFile("F:\files\file2.txt","GBK"); 

 val split: Array[String] = file.mkString.split(" ") 




3. Reading Network Resources, File Writing, Console Operation

1, read network resources

def main(args: Array[String]): Unit = { 
 val source: BufferedSource = Source.fromURL("") 
 val string: String = source.mkString 


2. File Writing Operation

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

 val writer = new PrintWriter("F:files\printWriter.txt") 

for(i <- 1 to 100){ 






3. Console Interaction

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

// Console Interaction -- Old API 

 Print ("Please enter content:") 

val consoleLine1 = Console.readLine() 

 Println ("What I just entered is:" + consoleLine1) 


// Console Interaction -- New API 

 Print ("Please enter content (new API):") 

 val consoleLine2 = StdIn.readLine() 

 Println ("What I just entered is:" + consoleLine2) 


4. Serialization in Scala

class Person extends Serializable{ 
 override def toString = name + "," + age 
 val name = "Nick" 
 val age = 20 

object PersonMain extends App{ 
 override def main(args: Array[String]): Unit = { 
import{FileOutputStream, FileInputStream, ObjectOutputStream, ObjectInputStream} 
 val nick = new Person 
 val out = new ObjectOutputStream(new FileOutputStream("Nick.obj")) 
val in = new ObjectInputStream(new FileInputStream("Nick.obj")) 
val saveNick = in.readObject() 

5. Regular expressions in Scala

We can match all matches in a sentence through regular expressions and output:

def main(args: Array[String]): Unit = { 
import scala.util.matching.Regex 
 val pattern1 = new Regex("(S|s)cala") 
 val pattern2 = "(S|s)cala".r 
 val str = "Scala is scalable and cool" 
 println((pattern2 findAllIn str).mkString(",")) 

The above is the whole content of this article. I hope it will be helpful to everyone’s study, and I hope you will support developpaer more.