Scala练习4 文件操作和正则表达式

2020-08-25  本文已影响0人  逸章

提示:如何编译和运行scala程序
D:\scalaproject\Test\src>scalac -d output one/two/three/Main.scala
D:\scalaproject\Test\src>scala -classpath output one.two.three.Main

文件读取

import scala.io.Source
import java.util.Scanner
import java.io.File
import java.io.FileInputStream

object Main extends App
{
    var source = Source.fromFile("D:\\what2.txt","UTF-8")
    
    //1.
//    for(oneChar <- source)
//    {
//       print(oneChar)
//    }
 
    //2.
//    val lineIterator = source.getLines();
//    
//    for(oneLine <- lineIterator)
//    {
//        println(oneLine)
//    }
    
    //3. if your file isn’t large, you can just read it into a string
//    val entireContents = source.mkString
//    println(entireContents)
    
    //4. 文件不能太大的前提下,把每个whitespace-separated token打印出来
//    val entireContents = source.mkString.split("\\s+")
//    entireContents.map(_.toInt)
//    val total = entireContents.reduceLeft((a,b) => a+b)
//    println("*************")
//    println(total)
    
    
    //5.peek at the next input character with the head method without consuming it
//    val bufferContent = source.buffered
//    for(oneChar <- bufferContent)
//    {
//      print(oneChar)
//    }
    
    //6. 我写的
    /*
     * Remember—you can always use the java.util.Scanner class to process a file that contains a mixture of text and numbers
     */
//    val s = new Scanner(new File("D:\\what2.txt"));
//    while(s.hasNext())
//    {
//      print(s.next())
//    }
//    s.close()
    
    //7.
//    print("How old are you? ")
//    val age = scala.io.StdIn.readInt()
//    println(age)
    
    //8. Reading Binary Files:Scala has no provision for reading binary files. You’ll need to use the Java library
//    val file = new File("D:\\what2.txt")
//    val in = new FileInputStream(file)
//    val bytes = new Array[Byte](file.length.toInt)
//    in.read(bytes)
//    in.close()
//    println(bytes(0)+" "+bytes(1)+" "+bytes(2)) //比如1输出为49,2输出50为,空格输出为32


    source.close()
}

文件写入

Scala has no built-in support for writing files. To write a text file, use a java.io.PrintWriter

val out = new PrintWriter("d:\\numbers.txt")
    for (i <- 1 to 20000) out.print(i)
      out.close()

Visiting Directories

The simplest approach is to use the Files.list and Files.walk methods of the java.nio.file package

import java.nio.file._

object Main extends App
{
    var dirname = "d:\\笔记"
    val entries = Files.walk(Paths.get(dirname)) // or Files.list
    try 
    {
        entries.forEach(p => println(p.getFileName))
    } 
    finally 
    {
        entries.close()
    }
}
image.png

序列化
In Java, serialization is used to transmit objects to other virtual machines or for short-term storage. (For long-term storage, serialization can be awkward—it is tedious to deal with different object versions as classes evolve over time.)

object Main extends App
{
    Creator.persistPerson(new Person("Yay","zhengfangzhonglu"))
}

@SerialVersionUID(42L)
class Person(val name:String, var address:String) extends Serializable
{    
}


object Creator
{
    //注意,参数不能加val或者var
    def persistPerson(person : Person)   
    {
        import java.io._
        val out = new ObjectOutputStream(new FileOutputStream("d:\\test.obj"))
        out.writeObject(person)
        out.close()
        val in = new ObjectInputStream(new FileInputStream("d:\\test.obj"))
        val savedFred = in.readObject().asInstanceOf[Person]
        println(s"name is ${savedFred.name}, and address is ${savedFred.address}")
    }
}

当我们忽略@SerialVersionUID annotation时(当然extends Serializable仍然需要),系统会提供一个默认的ID.

上一篇 下一篇

猜你喜欢

热点阅读