在成功案例中使用Scala贷款模式

问题描述 投票:0回答:1

我正在按照Alvin Alexander的教程使用Loan Pattern

这是我使用的代码 -

val year = 2016
val nationalData = {
val source = io.Source.fromFile(s"resources/Babynames/names/yob$year.txt")
    // names is iterator of String, split() gives the array
    //.toArray & toSeq is a slow process compare to .toSet  // .toSeq gives Stream Closed error
    val names = source.getLines().filter(_.nonEmpty).map(_.split(",")(0)).toSet
    source.close()      
    names
    // println(names.mkString(","))     
}   
println("Names " + nationalData)

val info = for (stateFile <- new java.io.File("resources/Babynames/namesbystate").list(); if stateFile.endsWith(".TXT")) yield {
    val source = io.Source.fromFile("resources/Babynames/namesbystate/" + stateFile)
    val names = source.getLines().filter(_.nonEmpty).map(_.split(",")).
        filter(a => a(2).toInt == year).map(a => a(3)).toArray // .toSet        
    source.close()      
    (stateFile.take(2), names)      
}
    println(info(0)._2.size + " names from state "+ info(0)._1)
    println(info(1)._2.size + " names from state "+ info(1)._1)
    for ((state, sname) <- info) {
     println("State: " +state + " Coverage of name in "+ year+" "+ sname.count(n => nationalData.contains(n)).toDouble / nationalData.size) // Set doesn't have length method
}

这就是我在上面的代码中应用readTextFilereadTextFileWithTry来学习/实验上述代码中的Loan Pattern的方法

def using[A <: { def close(): Unit }, B](resource: A)(f: A => B): B =
    try {
        f(resource)
    } finally {
        resource.close()
    }

def readTextFile(filename: String): Option[List[String]] = {
    try {
        val lines = using(fromFile(filename)) { source =>
            (for (line <- source.getLines) yield line).toList
        }
        Some(lines)
    } catch {
        case e: Exception => None
    }
}

def readTextFileWithTry(filename: String): Try[List[String]] = {
    Try {
        val lines = using(fromFile(filename)) { source =>
            (for (line <- source.getLines) yield line).toList
        }
        lines
    }
}

val year = 2016
val data = readTextFile(s"resources/Babynames/names/yob$year.txt") match {
    case Some(lines) =>
        val n = lines.filter(_.nonEmpty).map(_.split(",")(0)).toSet
        println(n)
    case None => println("couldn't read file")
}

val data1 = readTextFileWithTry("resources/Babynames/namesbystate")
data1 match {
    case Success(lines) => {
        val info = for (stateFile <- data1; if stateFile.endsWith(".TXT")) yield {
            val source = fromFile("resources/Babynames/namesbystate/" + stateFile)
            val names = source.getLines().filter(_.nonEmpty).map(_.split(",")).
                filter(a => a(2).toInt == year).map(a => a(3)).toArray // .toSet
            (stateFile.take(2), names)
            println(names)
        }
    }

但在第二种情况下,readTextFileWithTry,我收到以下错误 -

Failed, message is: java.io.FileNotFoundException: resources\Babynames\namesbystate (Access is denied)

我想失败的原因来自SO,我理解 - I am trying to open the same file on each iteration of the for loop

除此之外,我对我的使用方式几乎没有关注 -

  • 这是使用的好方法吗?有人可以帮助我如何在多个场合使用TRY?
  • 我试图改变readTextFileWithTry的返回类型,如Option[A]Set / Map或Scala Collection,以便稍后应用更高阶函数。但无法成功。不确定这是一个好习惯。
  • 如何在Success情况下使用高阶函数,因为有多个操作,在Success情况下代码块变大?我不能使用Success案件以外的任何领域。

有人能帮我理解吗?

scala file try-catch ioexception
1个回答
0
投票

我认为你的问题与“我试图在for循环的每次迭代中打开相同的文件”无关,它实际上与accepted answer中的相同

不幸的是,您没有提供堆栈跟踪,因此不清楚这是发生在哪一行。我猜想下降的电话是

val data1 = readTextFileWithTry("resources/Babynames/namesbystate")

并查看您的第一个代码示例:

val info = for (stateFile <- new java.io.File("resources/Babynames/namesbystate").list(); if stateFile.endsWith(".TXT")) yield {

它看起来像路径"resources/Babynames/namesbystate"指向一个目录。但在第二个示例中,您尝试将其作为文件读取,这就是错误的原因。它来自于你的readTextFileWithTry不是java.io.File.list电话的有效替代品。并且File.list不需要包装器,因为它不使用任何中间可关闭/一次性实体。

附:使用File.list(FilenameFilter filter)代替if stateFile.endsWith(".TXT"))可能更有意义

© www.soinside.com 2019 - 2024. All rights reserved.