• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala FileReader类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Scala中java.io.FileReader的典型用法代码示例。如果您正苦于以下问题:Scala FileReader类的具体用法?Scala FileReader怎么用?Scala FileReader使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了FileReader类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。

示例1: OfxParser

//设置package包名称以及导入依赖的类
package me.thethe.ofxparser

import java.io.{BufferedReader, FileReader}

import me.thethe.ofxparser.models.{Account, AccountType, Checking, NoType}
import net.sf.ofx4j.io.OFXHandler
import net.sf.ofx4j.io.nanoxml.NanoXMLOFXReader
import models.builders.{Account => AccountBuilder}

class OfxParser(filePath: String)  {
  val inputFileReader = new BufferedReader(new FileReader(filePath))
  val ofxParser = new NanoXMLOFXReader()

  def parse(handler: BankingOfxHandler): Account = {
    ofxParser.setContentHandler(handler)
    ofxParser.parse(inputFileReader)
    handler.account
  }
}

class BankingOfxHandler extends OFXHandler {
  var account: Account = null

  var accountBuilder: AccountBuilder = new AccountBuilder()

  override def onElement(name: String, value: String): Unit = {
    name match {
      case "ORG" => accountBuilder.bankName = value
      case "BANKID" => accountBuilder.aba = value
      case "ACCTID" => accountBuilder.accountId = value
      case "ACCTTYPE" => accountBuilder.accountType = value match {
        case "BANKING" => Checking
        case _ => NoType
      }
      case _ => ()
    }
    println(s"ELEMENT: $name, $value")
  }

  override def endAggregate(aggregateName: String): Unit = {
    aggregateName match {
      case "BANKACCTFROM" => account = Account(accountBuilder)
      case _ => ()
    }
    println(s"END AGGREGATE: $aggregateName")
  }

  override def onHeader(name: String, value: String): Unit = {
    println(s"HEADER: $name, $value")
  }

  override def startAggregate(aggregateName: String): Unit = {
    println(s"START AGGREGATE: $aggregateName")
  }
} 
开发者ID:jacksonja,项目名称:finance,代码行数:56,代码来源:OfxParser.scala


示例2: SerializationTest

//设置package包名称以及导入依赖的类
package org.argus.amandroid.serialization

import java.io.{FileReader, FileWriter}

import org.argus.amandroid.alir.componentSummary.ApkYard
import org.argus.amandroid.core.decompile.{ConverterUtil, DecompileLayout, DecompileStrategy, DecompilerSettings}
import org.argus.amandroid.core.model.ApkModel
import org.argus.jawa.core.DefaultReporter
import org.json4s.NoTypeHints
import org.json4s.native.Serialization
import org.json4s.native.Serialization.{read, write}
import org.scalatest.{FlatSpec, Matchers}
import org.argus.jawa.core.util.FileUtil


class SerializationTest extends FlatSpec with Matchers {

  "ApkModel" should "successfully serialized and deserialized" in {
    val apkFile = getClass.getResource("/icc-bench/IccHandling/icc_explicit_src_sink.apk").getPath
    val apkUri = FileUtil.toUri(apkFile)
    val outputUri = FileUtil.toUri(apkFile.substring(0, apkFile.length - 4))
    val reporter = new DefaultReporter
    val yard = new ApkYard(reporter)
    val layout = DecompileLayout(outputUri)
    val strategy = DecompileStrategy(layout)
    val settings = DecompilerSettings(debugMode = false, forceDelete = true, strategy, reporter)
    val apk = yard.loadApk(apkUri, settings, collectInfo = true)
    val model = apk.model
    implicit val formats = Serialization.formats(NoTypeHints) + ApkModelSerializer
    val apkRes = FileUtil.toFile(FileUtil.appendFileName(outputUri, "apk.json"))
    val oapk = new FileWriter(apkRes)
    try {
      write(model, oapk)
    } catch {
      case e: Exception =>
        e.printStackTrace()
    } finally {
      oapk.flush()
      oapk.close()
    }
    val iapk = new FileReader(apkRes)
    var newApkModel: ApkModel = null
    try {
      newApkModel = read[ApkModel](iapk)
    } catch {
      case e: Exception =>
        e.printStackTrace()
    } finally {
      iapk.close()
      ConverterUtil.cleanDir(outputUri)
    }
    require(
      model.getAppName == newApkModel.getAppName &&
      model.getComponents == newApkModel.getComponents &&
      model.getLayoutControls == newApkModel.getLayoutControls &&
      model.getCallbackMethods == newApkModel.getCallbackMethods &&
      model.getComponentInfos == newApkModel.getComponentInfos &&
      model.getEnvMap == newApkModel.getEnvMap)
  }
} 
开发者ID:arguslab,项目名称:Argus-SAF,代码行数:61,代码来源:SerializationTest.scala


示例3: FileReaderTest2Iterable

//设置package包名称以及导入依赖的类
import java.io.{FileWriter, BufferedReader, File, FileReader}

import org.scalatest._

class FileReaderTest2Iterable extends FlatSpec with Matchers {
  "Hello" should "have tests" in {


    def getContents(fileName: String): Iterable[String] = {
      val fr = new BufferedReader(new FileReader(fileName))
      new Iterable[String] {
        def iterator = new Iterator[String] {
          def hasNext = line != null

          def next = {
            val retVal = line
            line = getLine
            retVal
          }

          def getLine = {
            var line: String = null
            try {
              line = fr.readLine
            } catch {
              case _: Throwable => line = null; fr.close()
            }
            line
          }

          var line = getLine
        }
      }
    }


    val w = new FileWriter("/tmp/csv3.txt")

    Seq("/tmp/csv.txt", "/tmp/csv2.txt").foreach(fn => {
      getContents(fn).foreach(ln => {
        w.write(ln)
        w.write("\r\n")
      })
    }
    )


  }
} 
开发者ID:ralreiroe,项目名称:embarcadero,代码行数:50,代码来源:FileReaderTest2Iterable.scala


示例4: FileReaderTest3Iterator

//设置package包名称以及导入依赖的类
import java.io.{BufferedWriter, BufferedReader, FileReader, FileWriter}

import org.scalatest._

class FileReaderTest3Iterator extends FlatSpec with Matchers {
  "Hello" should "have tests" in {


    def getContents(fileName: String): Iterator[String] = {
      val fr = new BufferedReader(new FileReader(fileName))
      def iterator = new Iterator[String] {
        def hasNext = line != null

        def next = {
          val retVal = line
          line = getLine
          retVal
        }

        def getLine = {
          var line: String = null
          try {
            line = fr.readLine
          } catch {
            case _: Throwable => line = null; fr.close()
          }
          line
        }

        var line = getLine
      }
      iterator
    }

    val w = new BufferedWriter(new FileWriter("/tmp/csv4.txt"))

    Seq("/tmp/csv.txt", "/tmp/csv2.txt").foreach(fn => {
      getContents(fn).foreach(ln => {
        w.write(ln)
        w.write("\r\n")
      })
    }
    )


  }
} 
开发者ID:ralreiroe,项目名称:embarcadero,代码行数:48,代码来源:FileReaderTest3Iterator.scala


示例5: Main

//设置package包名称以及导入依赖的类
package org.metamath.scala

import java.io.FileReader

object Main {
  def main(args: Array[String]) {
    args match {
      case Array(file) =>
        val parser = new MMParser(new FileReader(file))
        println("File parsing...")
        implicit val db = parser.parse
        println("Verify...")
        new Verifier
        //println("Check definitions...")
        //new DefinitionChecker
      case _ => println("Usage: mm-scala file.mm")
    }
  }
} 
开发者ID:digama0,项目名称:mm-scala,代码行数:20,代码来源:Main.scala


示例6: FileLineTraversable

//设置package包名称以及导入依赖的类
package net.zhenglai.ml.lib

import java.io.{BufferedReader, File, FileReader}


class FileLineTraversable(file: File) extends Traversable[String] {
  val x = new FileLineTraversable(new File("test.txt"))

  override def foreach[U](f: (String) ? U): Unit = {
    val input = new BufferedReader(new FileReader(file))
    try {
      var line = input readLine

      if (line != null) {
        do {
          f(line)
          line = input readLine
        } while (line != null)
      }
    } finally {
      input close
    }
  }

  // when called within REPL, make sure entire file content aren't enumerated
  override def toString = s"{Lines of ${file getAbsolutePath}}"

  for {
    line ? x
    word ? line.split("\\s+")
  } yield word
} 
开发者ID:zhenglaizhang,项目名称:github-ml,代码行数:33,代码来源:FileLineTraversable.scala


示例7: ScalaExceptionHandling

//设置package包名称以及导入依赖的类
package com.chapter3.ScalaFP

import java.io.BufferedReader
import java.io.IOException
import java.io.FileReader

object ScalaExceptionHandling {
  def errorHandler(e:IOException){
    println("stop doing somehting!")
  }
  val file:String = "C:/Exp/input.txt"
  val input = new BufferedReader(new FileReader(file))
try {
  try {
    for (line <- Iterator.continually(input.readLine()).takeWhile(_ != null)) {
      Console.println(line)
    }
  } finally {
    input.close()
  }
} catch {
  case e:IOException => errorHandler(e)
}

  
} 
开发者ID:PacktPublishing,项目名称:Scala-and-Spark-for-Big-Data-Analytics,代码行数:27,代码来源:ScalaExceptionHandling.scala


示例8: TryCatch

//设置package包名称以及导入依赖的类
package com.chapter3.ScalaFP
import java.io.IOException
import java.io.FileReader
import java.io.FileNotFoundException
object TryCatch {
  def main(args: Array[String]) {
    try {
      val f = new FileReader("data/data.txt")
    } catch {
      case ex: FileNotFoundException => println("File not found exception")
      case ex: IOException => println("IO Exception") 
    } finally {
      println("Finally block always executes");
    }
  }
} 
开发者ID:PacktPublishing,项目名称:Scala-and-Spark-for-Big-Data-Analytics,代码行数:17,代码来源:TryCatchFinally.scala


示例9: ExceptionUtils

//设置package包名称以及导入依赖的类
package com.chsoft.common

import java.io.FileNotFoundException
import java.io.IOException
import java.io.FileReader

object ExceptionUtils {

  def main(args: Array[String]) {

    try {
      val f = new FileReader("input.txt")
    } catch {
      case ex: FileNotFoundException => {
        println("FileNotFoundException"+ex.getMessage)
      }
      case ex: IOException => {
        println("IOException")
      }
    }finally{  //finally ?????????????????????????????
      println("?????????????")
    }
    
    
  }
  
   def matchTest(x: Int){
      x match{
        case 1 if x<=4 => println("one")
        case 2 => println("two")
        //case _x => println("age"+_x)
        case _ => println("many")
      }
      
   }
  
} 
开发者ID:jacktomcat,项目名称:scala-practice,代码行数:38,代码来源:ExceptionUtils.scala


示例10: ParseBean

//设置package包名称以及导入依赖的类
package pl.writeonly.babel.beans

import java.io.BufferedReader
import java.io.FileReader
import javax.annotation.Resource
import pl.writeonly.babel.daos.DaoCsv
import au.com.bytecode.opencsv.CSVReader

@org.springframework.stereotype.Controller
class ParseBean {
  @Resource var daoCsv: DaoCsv = _
  def deen(fileName: String) = {
    //val reader = new BufferedReader(new FileReader(fileName))
    val reader = new CSVReader(new FileReader(fileName));
    val readed = reader.readAll()

    readed.foldLeft(new BufferList[_])((l, el) => { l})

  }
} 
开发者ID:writeonly,项目名称:babel,代码行数:21,代码来源:ParseBean.scala


示例11: AppProperties

//设置package包名称以及导入依赖的类
package com.esri

import java.io.{File, FileReader}
import java.util.Properties

import org.apache.spark.SparkConf

import scala.collection.JavaConverters._

object AppProperties {

  def loadProperties(filename: String, sparkConf: SparkConf = new SparkConf()) = {
    val file = new File(filename)
    if (file.exists) {
      val reader = new FileReader(file)
      try {
        val properties = new Properties()
        properties.load(reader)
        properties.asScala.foreach { case (k, v) => sparkConf.set(k, v) }
      }
      finally {
        reader.close()
      }
    }
    sparkConf
  }

} 
开发者ID:mraad,项目名称:spark-snap-points,代码行数:29,代码来源:AppProperties.scala


示例12: ParallelCoordinates

//设置package包名称以及导入依赖的类
import org.jfree.chart._
import org.jfree.data.xy._
import scala.math._
import scala.collection.mutable.{MutableList, Map}
import java.io.{FileReader, BufferedReader}

object ParallelCoordinates {
  def readCSVFile(filename: String): Map[String, MutableList[String]] = {
    val file = new FileReader(filename)
    val reader = new BufferedReader(file)
    val csvdata: Map[String, MutableList[String]] = Map()
    try {
      val alldata = new MutableList[Array[String]]
      var line:String = null
      while ({line = reader.readLine(); line} != null) {
        if (line.length != 0) {
          val delimiter: String = ","
          var splitline: Array[String] = line.split(delimiter).map(_.trim)
          alldata += splitline
        }
      }
      val labels = MutableList("sepal length", "sepal width",
        "petal length", "petal width", "class")
      val labelled = labels.zipWithIndex.map {
        case (label, index) => label -> alldata.map(x => x(index))
      }
      for (pair <- labelled) {
        csvdata += pair
      }
    } finally {
      reader.close()
    }
    csvdata
  }

  def main(args: Array[String]) {
    val data = readCSVFile("iris.csv")
    val dataset = new DefaultXYDataset
    for (i <- 0 until data("sepal length").size) {
      val x = Array(0.0, 1.0, 2.0, 3.0)
      val y1 = data("sepal length")(i).toDouble
      val y2 = data("sepal width")(i).toDouble
      val y3 = data("petal length")(i).toDouble
      val y4 = data("petal width")(i).toDouble
      val y = Array(y1, y2, y3, y4)
      val cls = data("class")(i)
      dataset.addSeries(cls + i, Array(x, y))
    }
    val frame = new ChartFrame("Parallel Coordinates",
      ChartFactory.createXYLineChart("Parallel Coordinates", "x", "y",
      dataset, org.jfree.chart.plot.PlotOrientation.VERTICAL,
      false, false, false))
    frame.pack()
    frame.setVisible(true)
  }
} 
开发者ID:PacktPublishing,项目名称:Scientific-Computing-with-Scala,代码行数:57,代码来源:plot.scala


示例13: CSVReader

//设置package包名称以及导入依赖的类
import scala.collection.mutable.{MutableList, Map}
import java.io.{FileReader, BufferedReader}

object CSVReader {
 def main(args: Array[String]) {
   val file = new FileReader("iris.csv")
   val reader = new BufferedReader(file)
   try {
     val alldata = new MutableList[Array[String]]
     var line:String = null
     while ({line = reader.readLine(); line} != null) {
       if (line.length != 0) {
         val delimiter: String = ","
         var splitline: Array[String] = line.split(delimiter).map(_.trim)
         alldata += splitline
       }
     }
     val labels = MutableList("sepal length", "sepal width",
       "petal length", "petal width", "class")
     val labelled = labels.zipWithIndex.map {
       case (label, index) => label -> alldata.map(x => x(index))
     }
     val csvdata: Map[String, MutableList[String]] = Map()
     for (pair <- labelled) {
       csvdata += pair                                           
     }
   }
   finally {
     reader.close()
   }
 }
} 
开发者ID:PacktPublishing,项目名称:Scientific-Computing-with-Scala,代码行数:33,代码来源:CSVReader.scala


示例14: readConfigFromArgs

//设置package包名称以及导入依赖的类
package pl.touk.nussknacker.engine.process.runner

import java.io.{File, FileReader}

import cats.data.Validated.{Invalid, Valid}
import com.typesafe.config.{Config, ConfigFactory}
import org.apache.commons.io.IOUtils
import pl.touk.nussknacker.engine.api.process.ProcessConfigCreator
import pl.touk.nussknacker.engine.canonicalgraph.CanonicalProcess
import pl.touk.nussknacker.engine.canonize.ProcessCanonizer
import pl.touk.nussknacker.engine.graph.EspProcess
import pl.touk.nussknacker.engine.marshall.ProcessMarshaller
import pl.touk.nussknacker.engine.util.ThreadUtils

trait FlinkRunner {

  private val ProcessMarshaller = new ProcessMarshaller


  protected def readConfigFromArgs(args: Array[String]): Config = {
    val optionalConfigArg = if (args.length > 1) Some(args(1)) else None
    readConfigFromArg(optionalConfigArg)
  }

  protected def loadCreator(config: Config): ProcessConfigCreator =
    ThreadUtils.loadUsingContextLoader(config.getString("processConfigCreatorClass")).newInstance().asInstanceOf[ProcessConfigCreator]

  protected def readProcessFromArg(arg: String): EspProcess = {
    val canonicalJson = if (arg.startsWith("@")) {
      IOUtils.toString(new FileReader(arg.substring(1)))
    } else {
      arg
    }
    ProcessMarshaller.fromJson(canonicalJson).toValidatedNel[Any, CanonicalProcess] andThen { canonical =>
      ProcessCanonizer.uncanonize(canonical)
    } match {
      case Valid(p) => p
      case Invalid(err) => throw new IllegalArgumentException(err.toList.mkString("Unmarshalling errors: ", ", ", ""))
    }
  }

  private def readConfigFromArg(arg: Option[String]): Config =
    arg match {
      case Some(name) if name.startsWith("@") =>
        ConfigFactory.parseFile(new File(name.substring(1)))
      case Some(string) =>
        ConfigFactory.parseString(string)
      case None =>
        ConfigFactory.load()
    }


} 
开发者ID:TouK,项目名称:nussknacker,代码行数:54,代码来源:FlinkRunner.scala


示例15: TraML

//设置package包名称以及导入依赖的类
package se.lth.immun

import java.io.File
import java.io.FileReader
import java.io.BufferedReader
import se.lth.immun.xml.XmlReader

import se.lth.immun.traml.ghost.GhostTraML
import se.lth.immun.diana.DianaLib

object TraML {
	
	import DianaLib._

	def parse(f:File) = {
		val r = new XmlReader(new BufferedReader(new FileReader(f)))
		val gt = GhostTraML.fromFile(r)
		
		for ((pk, transitions) <- gt.transitionGroups.toSeq) yield {
			val firstTrans = transitions.head
			Assay(
				pk.toString,
				gt.peptides(pk.pepCompId).proteins.mkString(";"),
				firstTrans.rt.map(_.t).getOrElse(0.0),
				pk.mz,
				firstTrans.q1z,
				gt.includeGroups.getOrElse(pk, Nil).map(gTarget =>
					Channel(gTarget.q1, gTarget.q1z, gTarget.id, 1, gTarget.intensity.getOrElse(
						throw new Exception("[%s] Couldn't parse target intensity".format(gTarget.id))
					))
				),
				transitions.map(gTrans =>
					Channel(gTrans.q3, gTrans.q3z, gTrans.id, 2, gTrans.intensity.getOrElse(
						throw new Exception("[%s] Couldn't parse transition intensity".format(gTrans.id))
					))
				)
			)
		}
	}
} 
开发者ID:ViktorSt,项目名称:diana2,代码行数:41,代码来源:TraML.scala


示例16: Person

//设置package包名称以及导入依赖的类
// These are meant to be typed into the REPL. You can also run
// scala -Xnojline < repl-session.scala to run them all at once.

class Person(val name: String = "", val age: Int = 0) {
  println("Just constructed another person")
  def description = name + " is " + age + " years old"
}

val p1 = new Person
val p2 = new Person("Fred") 
val p3 = new Person("Fred", 42) 
p1.description
p2.description
p3.description

import java.util.Properties
import java.io.FileReader

class MyProg {
  private val props = new Properties
  props.load(new FileReader("myprog.properties"))
    // The statement above is a part of the primary constructor
}

class Person(val name: String, private var age: Int) {
  def description = name + " is " + age + " years old"
  def birthday() { age += 1 }
}

val p = new Person("Fred", 42) 
p.name
p.age // Error--it's private
p.birthday()
p.description 
开发者ID:yeahnoob,项目名称:scala-impatient-2e-code,代码行数:35,代码来源:repl-session.scala


示例17: Dump

//设置package包名称以及导入依赖的类
package org.monarchinitiative.clique

import java.io.File

import org.backuity.clist._
import com.bigdata.rdf.sail.BigdataSail
import com.bigdata.rdf.sail.BigdataSailRepository
import java.util.Properties
import java.io.FileReader
import java.io.FileOutputStream
import org.openrdf.query.QueryLanguage
import java.io.BufferedOutputStream
import org.openrdf.rio.turtle.TurtleWriter


object Dump extends Command(description = "Dump Blazegraph database to a Turtle RDF file.") with Common {

  var file = arg[File](description = "File name for RDF output.")

  override def run(): Unit = {
    val blazegraphProperties = new Properties()
    blazegraphProperties.load(new FileReader(properties))
    val sail = new BigdataSail(blazegraphProperties)
    val repository = new BigdataSailRepository(sail)
    repository.initialize()
    val blazegraph = repository.getUnisolatedConnection
    val triplesQuery = blazegraph.prepareGraphQuery(QueryLanguage.SPARQL, "CONSTRUCT WHERE { ?s ?p ?o . }")
    val triplesOutput = new BufferedOutputStream(new FileOutputStream(file))
    triplesQuery.evaluate(new TurtleWriter(triplesOutput))
    triplesOutput.close()
    blazegraph.close()
  }

} 
开发者ID:balhoff,项目名称:clique-merge,代码行数:35,代码来源:Dump.scala


示例18: NpmPackage

//设置package包名称以及导入依赖的类
package scalajsbundler

import java.io.FileReader
import org.scalajs.core.tools.json
import org.scalajs.core.tools.json.{JSON, JSONDeserializer, JSONObjExtractor}
import sbt._
import scala.util.Try

case class NpmPackage(version: String) {
  def major: Option[Int] = {
    val r = """^(\d+)(\..*|)$""".r
    version match {
      case r(v, _) => Try(v.toInt).toOption
      case _ => None
    }
  }
}

object NpmPackage {
  implicit object NpmPackageDeserializer extends JSONDeserializer[NpmPackage] {
    def deserialize(x: JSON): NpmPackage = {
      val obj = new JSONObjExtractor(x)
      NpmPackage(
        obj.fld[String]("version")
      )
    }
  }

  def getForModule(targetDir: File, module: String): Option[NpmPackage] = {
    val webpackPackageJsonFilePath = targetDir / "node_modules" / module / "package.json"

    Try(json.fromJSON[NpmPackage](json.readJSON(new FileReader(webpackPackageJsonFilePath)))).toOption
  }
} 
开发者ID:scalacenter,项目名称:scalajs-bundler,代码行数:35,代码来源:NpmPackage.scala


示例19: CSVFile

//设置package包名称以及导入依赖的类
package koalas.csvfile

import java.io.{FileReader, InputStreamReader, BufferedReader}

object CSVFile{
  // def read(filePath: String, delimiter: String = ",", header: Boolean = true): List[List[String]] = {
  def read(
      filePath: String, delimiter: String = ",", header: Boolean = true,
      readerType: String = "File"): List[Map[String, String]] = {
    val reader = readerType match {
      case "File" => {
        val file = new FileReader(filePath)
        new BufferedReader(file)
      }
      case "InputStream" => {
        val inputStream = new InputStreamReader(getClass().getResourceAsStream(filePath))
        new BufferedReader(inputStream)
      }
    }

    var data: List[List[String]] = List.empty
    // var row: List[String] = List()

    try {
      var line: String = null
      while ({line = reader.readLine(); line} != null) {
        // Eventually fix this to allow delimiters inside string objects
        val row: List[String] = line.split(delimiter).map(_.trim).toList
        data = data :+ row
      }
    } finally {
      reader.close()
    }

    type HeadTailSplit = Tuple2[List[String], List[List[String]]]
    val (columns, dataTail): HeadTailSplit = if (header) {
      (data.head, data.tail)
    } else {
      val columns = List.range(0, data.head.length).map(_.toString)
      (columns, data)
    }
    dataTail.map(row => columns.zip(row).toMap)
  }
  def write(path: String): Unit = {}
} 
开发者ID:gvoronov,项目名称:koalas,代码行数:46,代码来源:CSVFile.scala


示例20: ContextRecoMatrices

//设置package包名称以及导入依赖的类
package processing

import java.io.{BufferedReader, FileReader, PrintWriter}

import org.jblas.DoubleMatrix


object ContextRecoMatrices {

  def load(file: String): Array[DoubleMatrix] = {
    val reader: BufferedReader = new BufferedReader(new FileReader(file))
    val d: Int = Integer.parseInt(reader.readLine())
    val res = new Array[DoubleMatrix](d)
    def readMatrix: DoubleMatrix = {
      val dimension: Array[Int] = reader.readLine().split(",").map(_.toInt)
      new DoubleMatrix(dimension(0), dimension(1), reader.readLine().split(",").map(_.toDouble): _*)
    }
    for (i <- 0 until d) {
      res(i) = readMatrix
    }
    return res
  }

  def save(file: String, m: Array[DoubleMatrix]): Unit = {
    val f = new PrintWriter(file)
    f.println(m.length)
    for (i <- 0 until m.length) {
      f.println(s"${m(i).rows},${m(i).columns},${m(i).length}")
      m(i).data.foreach { x => f.print(x); f.print(",") }
      f.println()
    }
    f.close()
  }
} 
开发者ID:srihari,项目名称:recommendr,代码行数:35,代码来源:ContextRecoMatrices.scala



注:本文中的java.io.FileReader类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala URLDecoder类代码示例发布时间:2022-05-23
下一篇:
Scala RunMode类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap