首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Scala中读取资源文件夹中的文件?

如何在Scala中读取资源文件夹中的文件?
EN

Stack Overflow用户
提问于 2014-12-08 23:12:17
回答 4查看 139.1K关注 0票数 123

我有一个如下所示的文件夹结构:

代码语言:javascript
复制
- main
-- java
-- resources 
-- scalaresources
--- commandFiles 

在这些文件夹中,我有我必须读取的文件。代码如下:

代码语言:javascript
复制
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
    }
  }
}
EN

回答 4

Stack Overflow用户

发布于 2016-12-08 19:32:49

对于Scala >= 2.12,使用Source.fromResource

代码语言:javascript
复制
scala.io.Source.fromResource("located_in_resouces.any")
票数 33
EN

Stack Overflow用户

发布于 2018-11-19 21:53:24

Scala >= 2.12的单行解决方案

代码语言:javascript
复制
val source_html = Source.fromResource("file.html").mkString
票数 18
EN

Stack Overflow用户

发布于 2018-08-04 22:18:08

代码语言:javascript
复制
import scala.io.Source

object Demo {

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

    val ipfileStream = getClass.getResourceAsStream("/folder/a-words.txt")
    val readlines = Source.fromInputStream(ipfileStream).getLines
    readlines.foreach(readlines => println(readlines))

  }

}
票数 9
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27360977

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档