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

时间:2014-12-08 15:12:17

标签: scala scala-collections

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

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

在那个文件夹中我有我必须阅读的文件。 这是代码:

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
    }
  }
}

6 个答案:

答案 0 :(得分:164)

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

示例文件夹结构:

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

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

要读取资源,对象来源会提供方法 fromResource

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

在2.12之前读取资源(由于jar兼容性,仍然是我最喜欢的)

要阅读资源,您可以使用 getClass.getResource getClass.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,请考虑:

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))
 }

很高兴知道

请注意,当资源是 jar getResource 的一部分时, getResourceAsStream 也能正常工作,它会返回一个经常显示的网址用于创建文件可能会导致问题。

生产中的

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

答案 1 :(得分:25)

对于Scala> = 2.12,请使用(function () { 'use strict' angular.module("GAiiNSApp").controller("ProdPerDash", ['$http', '$scope', '$log', function ($http, $scope, $log) { $scope.isLoading = false; $scope.hideme = true; var currentdate = new Date(); var startdd = "01"; var startmonth = "00"; var lastyear = currentdate.getFullYear() - 3; var enddd = "31"; var endmonth = "11"; var endyear = currentdate.getFullYear(); $scope.StartDate = new Date(lastyear, startmonth, startdd); $scope.EndDate = new Date(endyear, endmonth, enddd); $scope.Region = "Local"; $scope.Country = ""; $scope.ProductLineSelected = false; $scope.ButtonText = "CUSTOMIZE"; $scope.clicked = false; $scope.Yes = function () { if (!$scope.clicked == true) { $scope.ButtonText = "CANCEL"; $scope.clicked = true; } else { $scope.ButtonText = "CUSTOMIZE"; $scope.clicked = false; } } $scope.alert = function (message) { $window.alert(message); } $scope.Regions = ["Export", "Local"]; $http.get('/General/API/GetProductDivision').then(function (res) { $scope.listofProd = res.data; }); $scope.selectedProduct = ""; $scope.generateChart = function (prodname) { $scope.selectedProduct = prodname; $scope.isLoading = true; $http.get('/Marketing/MarketingAPI/ProdPerformance', { params: { StartDate: $scope.StartDate, EndDate: $scope.EndDate, ProductDivision: prodname, Division: $scope.Region, Area: $scope.Country } }).then(function (res) { var resArray = res.data; var trendarray = []; $scope.TableRecords = resArray; $scope.hideme = false; var json = resArray; // console.log("Array of Objects: " + JSON.stringify($scope.TableRecords)); var groupedData = {}; var result = []; resArray.forEach(function (item) { var year = item.SecuredYear; var value = item.ValueInDhs; if (groupedData.hasOwnProperty(year)) { groupedData[year] += value; } else { groupedData[year] = value; } }); //Pie chart data starts here var years = []; json.forEach(function (obj) { if (years.indexOf(obj.SecuredYear) == -1) years.push(obj.SecuredYear); }); //$scope.years = years; $scope.years = angular.copy(years); $scope.pichartsview = true; $scope.myFunction = function (index) { var data = [['Product', 'ValueInDhs']]; json.forEach(function (obj) { if (obj.SecuredYear == years[index]) { data.push([String(obj.GroupName).trim(), obj.ValueInDhs]); } }); $scope.displayChart(data, index); } $scope.displayChart = function (dataForChart, index) { var chartData = dataForChart; google.charts.load('current', { 'packages': ['corechart'] }); google.charts.setOnLoadCallback(drawChartPie); function drawChartPie() { var data = google.visualization.arrayToDataTable(chartData); var options = { chartArea: { left: 10, top: 20, width: "80%", height: "80%" }, legend: 'bottom', is3D: true, pieSliceText: 'percentage', pieSliceTextStyle: { fontSize: 8 }, title: $scope.selectedProduct + " - " + $scope.years[index] }; var chart = new google.visualization.PieChart(document.getElementById('piechart' + index)); $scope.$apply(function () { chart.draw(data, options); }); } } //Pie chart data ends here for (var year in groupedData) { var tmp = {}; tmp[year] = groupedData[year]; result.push(tmp); } result.forEach(function (obj, index) { var key = Object.keys(obj)[0]; trendarray.push([parseInt(key, 10), obj[key]]); }); trendarray.splice(0, 0, [{ label: 'SecuredYear', type: 'number' }, { label: 'ValueInDhs', type: 'number' }]); google.charts.load('current', { 'packages': ['corechart'] }); google.charts.setOnLoadCallback(drawChart); $scope.isLoading = false; function drawChart() { var data = google.visualization.arrayToDataTable( trendarray ); var options = { legend: 'none', title: 'Product Performance Trendline - ' + $scope.selectedProduct + " - " + $scope.Region, hAxis: { title: 'Secured Year', format: '0' }, vAxis: { title: 'Secured Value in DHS' }, trendlines: { 0: { lineWidth: 5, type: 'polynomial', visibleInLegend: true, color: 'green', } } }; var chart = new google.visualization.ScatterChart(document.getElementById('chart_div2')); chart.draw(data, options); } }) $scope.ProductLineSelected = true; }; }]); //this is ctrl closing })(); //this is function closing

Source.fromResource

答案 2 :(得分:6)

Scala的Onliner解决方案> = 2.12

val source_html = Source.fromResource("file.html").getLines().mkString("\n")

答案 3 :(得分:3)

import scala.io.Source

object Demo {

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

    val fileStream = getClass.getResourceAsStream("/json-sample.js")
    val lines = Source.fromInputStream(fileStream).getLines
    lines.foreach(line => println(line))

  }

}

enter image description here

答案 4 :(得分:1)

对于 Scala 2.11 ,如果getLines不能完全满足您的要求,您还可以将文件从jar中复制到本地文件系统中。

这是一个片段,可以从/ resources读取google .p12格式的二进制API密钥,然后将其写入/ tmp,然后使用文件路径字符串作为spark-google-spreadsheets write的输入。 / p>

sbt-native-packagersbt-assembly的世界中,复制到本地对scalatest二进制文件测试也很有用。只需将它们从资源中弹出到本地,运行测试,然后删除即可。

import java.io.{File, FileOutputStream}
import java.nio.file.{Files, Paths}

def resourceToLocal(resourcePath: String) = {
  val outPath = "/tmp/" + resourcePath
  if (!Files.exists(Paths.get(outPath))) {
    val resourceFileStream = getClass.getResourceAsStream(s"/${resourcePath}")
    val fos = new FileOutputStream(outPath)
    fos.write(
      Stream.continually(resourceFileStream.read).takeWhile(-1 !=).map(_.toByte).toArray
    )
    fos.close()
  }
  outPath
}

val filePathFromResourcesDirectory = "google-docs-key.p12"
val serviceAccountId = "[something]@drive-integration-[something].iam.gserviceaccount.com"
val googleSheetId = "1nC8Y3a8cvtXhhrpZCNAsP4MBHRm5Uee4xX-rCW3CW_4"
val tabName = "Favorite Cities"

import spark.implicits
val df = Seq(("Brooklyn", "New York"), 
          ("New York City", "New York"), 
          ("San Francisco", "California")).
          toDF("City", "State")

df.write.
  format("com.github.potix2.spark.google.spreadsheets").
  option("serviceAccountId", serviceAccountId).
  option("credentialPath", resourceToLocal(filePathFromResourcesDirectory)).
  save(s"${googleSheetId}/${tabName}")

答案 5 :(得分:0)

可以从以下位置从scala的资源文件夹中访问所需文件

val file = scala.io.Source.fromFile(s"src/main/resources/app.config").getLines().mkString