如何从 Scala 的资源文件夹中读取文件? [英] How to read files from resources folder in Scala?

查看:56
本文介绍了如何从 Scala 的资源文件夹中读取文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的文件夹结构如下:

- main
-- java
-- resources 
-- scalaresources
--- commandFiles 

在那个文件夹中我有我必须阅读的文件.代码如下:

and in that folders I have my files that I have to read. Here is the code:

def readData(runtype: String, snmphost: String, comstring: String, specificType:  String): Unit = {
  val realOrInvFile = "/commandFiles/snmpcmds." +runtype.trim // these files are under commandFiles folder, which I have to read. 
    try {
      if (specificType.equalsIgnoreCase("Cisco")) {
        val specificDeviceFile: String = "/commandFiles/snmpcmds."+runtype.trim+ ".cisco"
        val realOrInvCmdsList = scala.io.Source.fromFile(realOrInvFile).getLines().toList.filterNot(line => line.startsWith("#")).map{
          //some code 
        }
        val specificCmdsList = scala.io.Source.fromFile(specificDeviceFile).getLines().toList.filterNot(line => line.startsWith("#")).map{
          //some code
        }
      }
    } catch {
      case e: Exception => e.printStackTrace
    }
  }
}

推荐答案

Scala 中的资源与 Java 中的资源完全一样.最好遵循 Java 最佳实践并将所有资源放在 src/main/resourcessrc/test/resources 中.

Resources in Scala work exactly as they do in Java. It is best to follow the Java best practices and put all resources in src/main/resources and src/test/resources.

示例文件夹结构:

testing_styles/
├── build.sbt
├── src
│   └── main
│       ├── resources
│       │   └── readme.txt

Scala 2.12.x &&2.13.x 读取资源

为了读取资源,对象Source提供了fromResource方法.

import scala.io.Source
val readmeText : Iterator[String] = Source.fromResource("readme.txt").getLines

阅读 2.12 之前的资源(由于 jar 兼容性仍然是我的最爱)

要读取资源,您可以使用 getClass.getResourcegetClass.getResourceAsStream.

val stream: InputStream = getClass.getResourceAsStream("/readme.txt")
val lines: Iterator[String] = scala.io.Source.fromInputStream( stream ).getLines

更好的错误反馈 (2.12.x && 2.13.x)

为了避免不可调试的 Java NPE,请考虑:

nicer error feedback (2.12.x && 2.13.x)

To avoid undebuggable Java NPEs, consider:

import scala.util.Try
import scala.io.Source
import java.io.FileNotFoundException

object Example {

  def readResourceWithNiceError(resourcePath: String): Try[Iterator[String]] = 
    Try(Source.fromResource(resourcePath).getLines)
      .recover(throw new FileNotFoundException(resourcePath))
 }

很高兴知道

请记住,当资源是 jargetResource 的一部分时,getResourceAsStream 也能正常工作,getResource 返回的 URL 通常是用于创建文件可能会导致出现问题.

good to know

Keep in mind that getResourceAsStream also works fine when the resources are part of a jar, getResource, which returns a URL which is often used to create a file can lead to problems there.

在生产代码中,我建议确保再次关闭源代码.

In production code I suggest to make sure that the source is closed again.

这篇关于如何从 Scala 的资源文件夹中读取文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆