Implementation of File Operation and Network Request in Scala

Time:2019-10-8

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){ 

 println(line) 

 } 

// Pay attention to closing files 

file.close() 

}

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(" ") 

 println(split.mkString("\t")) 

 file.close() 

}

3. Reading Network Resources, File Writing, Console Operation

1, read network resources


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

 println(string) 
 source.close() 
}

2. File Writing Operation


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

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

for(i <- 1 to 100){ 

 writer.println(i) 

 writer.flush() 

 } 

 writer.close() 

}

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


@SerialVersionUID(1L) 
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 java.io.{FileOutputStream, FileInputStream, ObjectOutputStream, ObjectInputStream} 
 val nick = new Person 
 val out = new ObjectOutputStream(new FileOutputStream("Nick.obj")) 
out.writeObject(nick) 
out.close() 
 
val in = new ObjectInputStream(new FileInputStream("Nick.obj")) 
val saveNick = in.readObject() 
in.close() 
println(saveNick) 
 } 
}

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.