Scala file read-write operations and regular expressions

Source: Internet
Author: User
Tags readfile java printwriter

Directory

In this blog you will learn and understand commonly used file processing tasks, such as reading a line of text files, the main points of this blog include:

    1. Source.fromfile (...). Getlines.toarray output file All lines
    2. Source.fromfile (...). Mkstring output file contents as a string
    3. To convert a string to a number, you can use the ToInt or ToDouble method
    4. Writing a text file using Java PrintWriter
    5. "Regular". R is a Regex object
    6. If your regular expression contains a backslash or quotation mark, use "" "" "" "" ""
    7. Regular patterns contain groupings, which can be used for (Regex (variable 1 ..., variable 2) <-strings)

The main points of this blog are as follows:

Read rows
Read all the rows of the file, you can call the Getlines method of the Scala.io.Source object: Val Source = Source.fromfile ("A.txt", "Utf-8") val lineiterator = The source.getlines result is that iterators can use a for loop to process these lines for (i <-lineiterator) println (i) or use iterators to apply ToArray or Tobuffer methods, Put these lines into the array force or array buffer row, if you want to read the file as a string, just val conents = source.mkstring Below is a simple code instance: Read A.txtobject ReadFile {def main on the desktop ( Args:array[string]): Unit = {val Read = new ReadFile () val resource:string = "C:\\users\\donniegao\\desktop\\a.tx T "val encode =" UTF-8 "read.readfile (Resource, encode) println (read.readfiletostr (Resource, encode))}}class Re Adfile {/** * line reads the contents of the file * * @param resource file path * @param code file Encoding format */def readFile (resource:str      ING, code:string): Unit = {var Source:bufferedsource = null try {//Gets the file's source object, the first parameter is the path of the file, and the second file is encoded in the format Source = Source.fromfile (resource, code) Val lineiterator = Source.getlines () while (true) {if (linei Terator.hasnext) {println (Lineiterator.next ())} else {return}}} finally {//frees Resource Source.close ()}}/** * All contents of the text file as strings * * @param resource file path * @param code file Encoding format * @return */def readfiletostr (resource:string, code:st Ring): String = {//Gets the source object of the file, the first parameter is the path of the file, the second file is encoded in the format var Source:bufferedsource = null try {Source = S Ource.fromfile (resource, code) source.mkstring} finally {Source.close ()}}}
Read characters

To read a single character in a file, you can treat the source object as an iterator, and if you just want to see the characters you can call the buffered method of the source object.

Reading lexical units and numbers
读取源文件中所有空格隔开的词法单元val tokens = source.mkString.split("\\s+")若有个基本都是浮点型的文件,可以将其读取到数组中:val numbers = for (w <- tokens) yield w.toDouble 或者也可 val numbers = token.map(_.toDouble)
To read a binary file

Scala does not provide a way to read binary files, you can use Java to read binary methods, code examples

val file = new File(fileName)val in = new FileInputStream(file)val bytes = new Array[Byte](file.length.toInt)in.read(bytes)in.close()
Writing to a text file

Scala does not have built-in support for writing files, and can be used for file write operations such as using Java.io.PrintWriter

  /**    * Scala写入文借助java的PrintWriter    */  def write(): Unit = {    val out = new PrintWriter("C:\\Users\\DonnieGao\\Desktop\\test.txt")    for (i <- 0 to 100) out.println(i)    out.close()  }
Accessing the file directory

Scala does not have direct access to all files in a directory or recursively traverse a directory class

  /**    * 使用java列举下所有的文件夹    * @param dir 文件目录路径    */  def dir(dir:String) = {    val dirFile = new File(dir)   val arrayFile= dirFile.listFiles()    for (i <- arrayFile){println(arrayFile.toBuffer)}  }
Serialization of

Declaring a class in Java that can be a sequence number is usually the following:

public class Person implements java.io.Serializable {    private static final long serialVersionUID = 4436475322569107137L;}Scala中声明一个可以被序列化的类通常是下面这种:@SerialVersionUID(12356L) class ReadFile extends Serializable {    }
Regular expressions

The regular manipulation of Scala.util.matching.Regex in Scala makes this thing easy. Constructs a Regex object, using the R method of the string class to

  object Regexdemo {def main (args:array[string]): Unit = {//Initialize regular object val numpattern = "[0 -9]+ ". r val Regex =" Welcome to Beijing "//Findallin method returns a traversal of all matching iterators, which can be used for the For loop (matchstring <-Numpatt Ern.findallin (regex)) {println (matchstring)}//query string first match println (Numpattern.findfirstin (regex))//Check The starting part of a string can match, you can use Findprefixof println (Numpattern.findprefixof (regex))}  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.