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

Scala BufferedReader类代码示例

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

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



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

示例1: CommandReader

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

import java.io.BufferedReader
import java.io.InputStreamReader
import java.io.InputStream

import pubsub.Client

class CommandReader(inStream: InputStream, client: Client) {
  val inputBuffer = new BufferedReader(new InputStreamReader(inStream))

  def fetchCommand(): Command = {
    val line = inputBuffer.readLine()

    if (line == null || line.startsWith("leave")) {
      EndOfClient(client)
    }
    else {
      val quoteIndex = line.indexOf('\'')
      val hasPayload = quoteIndex != -1
      val parts =
        if(!hasPayload) {
          line.split(" ").toList
        } else {
          val (command, payload) = line.splitAt(quoteIndex)
          command.split(" ").toList :+ payload
        }

      parts match {
        case "subscribe" :: topic :: Nil   => Subscribe(topic, client)
        case "unsubscribe" :: topic :: Nil => Unsubscribe(topic, client)
        case "rename" :: newName :: Nil    => Rename(newName, client)

        case "publish" :: topic :: msg :: Nil if hasPayload && msg != "\'" =>
          var message = msg
          while(!message.endsWith("\'")) {
            message += "\n" + inputBuffer.readLine()
          }
          Publish(topic, message, client)

        case _ => MalformedCommand(client)
      }
    }
  }
} 
开发者ID:vincenzobaz,项目名称:Parallelism-and-Concurrency-Assignments,代码行数:46,代码来源:CommandReader.scala


示例2: MedicineProcess

//设置package包名称以及导入依赖的类
package cn.com.warlock.practice.ml

import java.io.BufferedReader
import java.nio.charset.StandardCharsets
import java.nio.file.{Files, Paths}

import org.apache.spark.ml.UnaryTransformer
import org.apache.spark.ml.param.ParamMap
import org.apache.spark.ml.util.Identifiable
import org.apache.spark.sql.types.{ArrayType, DataType, StringType}

import scala.collection.mutable.Set

class MedicineProcess(override val uid: String, private val dict: String)
  extends UnaryTransformer[Seq[String], Seq[String], MedicineProcess] {

  def this(dict: String) = this(Identifiable.randomUID("med"), dict)

  // ?????????
  private val wordsSet = loadDict

  // ????
  private def loadDict: Set[String] = {
    val br: BufferedReader = Files.newBufferedReader(Paths.get(dict), StandardCharsets.UTF_8)
    val words = Set[String]()

    var count = 0

    while (br.ready()) {
      words += br.readLine()
      count += 1
    }

    println(s"load med words: $count")

    words
  }

  override protected def createTransformFunc: Seq[String] => Seq[String] = (words: Seq[String]) => {
    // ?? "???", arr ?????????, c ??????? word
    words.foldLeft(List[String]())((arr, c) => {
      val newC = wordsSet.contains(c) match {
        case true => List(c, "_MED_")
        case false => List(c)
      }
      arr ++ newC
    })
  }

  override protected def validateInputType(inputType: DataType): Unit = {
    require(inputType.isInstanceOf[ArrayType],
      s"The input column must be ArrayType, but got $inputType.")
  }

  override protected def outputDataType: DataType = new ArrayType(StringType, true)

  override def copy(extra: ParamMap): MedicineProcess = defaultCopy(extra)
} 
开发者ID:warlock-china,项目名称:spark-meepo,代码行数:59,代码来源:MedicineProcess.scala


示例3: foo

//设置package包名称以及导入依赖的类
import java.io.BufferedReader
import java.io.InputStreamReader
import java.io.IOException

def foo: String = {
  	val in = new BufferedReader(new InputStreamReader(System.in))
 	try {
		print("Escribe texto: ")
		in.readLine
  	}
  	catch {
    	case e: IOException => { e.printStackTrace(); e.toString() }
  	}
  	finally {
    	in.close()
  	}
}

println("Return value: " + foo) 
开发者ID:romanarranz,项目名称:NTP,代码行数:20,代码来源:excepcionesTryCatchFinally.scala


示例4: 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


示例5: DDApp

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

import com.virdis.{ProcessTokens, resourceManager}
import opennlp.tools.sentdetect.{SentenceDetectorME, SentenceModel}
import opennlp.tools.tokenize.{TokenizerME, TokenizerModel, WhitespaceTokenizer}


object DDApp extends ProcessTokens {


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

    println("")
    println("")
    println("Application ready .....".toUpperCase())
    println("Type in your text.")
    println("Once you are done inputting your text, go to a new line (ENTER) and then type :q or :quit to begin processing.")
    println("")
    println("")
    resourceManager.using(new BufferedReader(new InputStreamReader(System.in))) {
      stdInReader =>
        var running = true
        val buffer = new StringBuilder()
        val whiteSpaceTokenizer = WhitespaceTokenizer.INSTANCE

        resourceManager.using(new FileInputStream("lib/en-sent.bin")) {
          trainedSM =>
            val sentenceDetect = new SentenceDetectorME(new SentenceModel(trainedSM))

              while (running) {
                val line = stdInReader.readLine()
                if (line.equals(":quit") || line.equals(":q")) {
                  running = false
                  val resMap = processTokens(buffer, sentenceDetect, whiteSpaceTokenizer)

                  prettyPrinting(resMap)

                } else {
                  buffer.append(line.toLowerCase())
                  buffer.append("\n")
                }
              }
        }

    }

    System.exit(0)
  }
} 
开发者ID:virdis,项目名称:ddl-concordance,代码行数:50,代码来源:DDApp.scala


示例6: JVMUtil

//设置package包名称以及导入依赖的类
package org.argus.jawa.core.util

import java.io.{BufferedReader, InputStreamReader}
import java.net.URLClassLoader
import java.text.NumberFormat

 
object JVMUtil {
	def startSecondJVM[C](clazz: Class[C], jvmArgs: List[String], args: List[String], redirectStream: Boolean): Int = {
    val separator = System.getProperty("file.separator")
    val classpath = Thread.currentThread().getContextClassLoader.asInstanceOf[URLClassLoader].getURLs.map(_.getPath()).reduce((c1, c2) => c1 + java.io.File.pathSeparator + c2)
    val path = System.getProperty("java.home") + separator + "bin" + separator + "java"
    val commands: IList[String] = List(path) ::: jvmArgs ::: List("-cp", classpath, clazz.getCanonicalName.stripSuffix("$")) ::: args
    import scala.collection.JavaConverters._
    val processBuilder = new ProcessBuilder(commands.asJava)
    processBuilder.redirectErrorStream(redirectStream)
    val process = processBuilder.start()
    val is = process.getInputStream
    val isr = new InputStreamReader(is)
    val br = new BufferedReader(isr)
    var line = br.readLine()
    while (line != null) {
      println(line)
      line = br.readLine()
    }
    process.waitFor()
  }
  
  def showMemoryUsage(): Unit = {
    val runtime = Runtime.getRuntime
    val format = NumberFormat.getInstance()
    
    val sb = new StringBuilder()
    val maxMemory = runtime.maxMemory()
    val allocatedMemory = runtime.totalMemory()
    val freeMemory = runtime.freeMemory()
    
    sb.append("free memory: " + format.format(freeMemory / 1024 / 1024) + " ")
    sb.append("allocated memory: " + format.format(allocatedMemory / 1024 / 1024) + " ")
    sb.append("max memory: " + format.format(maxMemory / 1024 / 1024) + " ")
    sb.append("total free memory: " + format.format((freeMemory + (maxMemory - allocatedMemory)) / 1024 / 1024) + " ")
    println(sb.toString())
  }
} 
开发者ID:arguslab,项目名称:Argus-SAF,代码行数:45,代码来源:JVMUtil.scala


示例7: ProcessRunner

//设置package包名称以及导入依赖的类
package tech.artemisia.task.localhost.util

import java.io.{BufferedReader, File, InputStreamReader}
import scala.collection.JavaConversions._


class ProcessRunner(val interpreter: String = "/bin/sh") {

  def executeInShell(cwd: String = System.getProperty("user.home"), env: Map[String, String] = Map())(body : String): (String,String,Int) = {
    val pb = new  ProcessBuilder()
    pb.directory(new File(cwd))
    pb.redirectOutput(ProcessBuilder.Redirect.PIPE)
    pb.redirectError(ProcessBuilder.Redirect.PIPE)
    val env_variables = pb.environment()
    env map { vars => env_variables.put(vars._1,vars._2) }
    pb.command(interpreter :: "-c" :: s""" " ${body.split(System.getProperty("line.separator")).filter(_.trim.length > 0).mkString(" ; ")} " """ :: Nil)
    this.execute(pb)
  }

  def executeFile(cwd: String = System.getProperty("user.home"), env: Map[String, String] = Map())(file: String): (String,String,Int) = {
    val pb = new  ProcessBuilder()
    pb.directory(new File(cwd))
    pb.redirectOutput(ProcessBuilder.Redirect.PIPE)
    pb.redirectError(ProcessBuilder.Redirect.PIPE)
    val env_variables = pb.environment()
    env map { vars => env_variables.put(vars._1,vars._2) }
    pb.command(interpreter :: file :: Nil)
    this.execute(pb)

  }

  private def execute(pb: ProcessBuilder) : (String,String,Int) = {
    val process = pb.start()
    val stdout_buffer = new BufferedReader( new InputStreamReader(process.getInputStream))
    val stderr_buffer = new BufferedReader( new InputStreamReader(process.getErrorStream))
    val stdout = Stream.continually(stdout_buffer.readLine()).takeWhile(_ != null).mkString(System.getProperty("line.separator"))
    val stderr = Stream.continually(stderr_buffer.readLine()).takeWhile(_ != null).mkString(System.getProperty("line.separator"))
    val return_code = process.waitFor()
    (stdout,stderr,return_code)
  }

} 
开发者ID:gitter-badger,项目名称:artemisia,代码行数:43,代码来源:ProcessRunner.scala


示例8: 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


示例9: 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


示例10: 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


示例11: 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


示例12: GccRunner

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

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

import scala.collection.mutable.ListBuffer

class GccRunner(a: Unit, config: Config) extends Phase[Unit] {
  override protected def getResult(): Unit = {
    val gcc = Runtime.getRuntime.exec(s"gcc -m64 -Wl,-e,main -nostdlib -o ${config.outFile} ${config.asmOutFile}")
    val stderr = new BufferedReader(new InputStreamReader(gcc.getErrorStream))
    gcc.waitFor()
    val stream = Stream.continually(stderr.readLine()).takeWhile(_ != null)
    if (gcc.exitValue() != 0 || stream.nonEmpty) {
      _findings += new Finding() {
        override def pos: Position = Position.NoPosition
        override def msg: String = s"GCC returned exit status ${gcc.exitValue}\n${stream.mkString("\n")}"
        override def severity: Severity = Severity.ERROR
      }
    }
  }

  val _findings = ListBuffer[Finding]()

  override def findings: List[Finding] = _findings.toList

  override def dumpResult(writer: BufferedWriter): Unit = {}
} 
开发者ID:jspam,项目名称:mjis,代码行数:28,代码来源:GccRunner.scala


示例13: RecordBean

//设置package包名称以及导入依赖的类
package pl.writeonly.babel.beans
import javax.annotation.Resource
import java.io.BufferedReader
import org.springframework.stereotype.Service
import pl.writeonly.babel.daos.DaoCrud
import pl.writeonly.babel.entities.Record
import pl.writeonly.babel.entities.User
import pl.writeonly.scala.util.ToBoolean
import scala.collection.mutable.MutableList
import pl.writeonly.babel.entities.Relation

@org.springframework.stereotype.Service
class RecordBean(@Resource(name = "daoImpl") val dao: DaoCrud) extends ToBoolean {
  val clazz = classOf[Record]
  def persist(record: Record) = dao.persist(record)
  def persistAll(records: List[Record]) = dao.persistAll(records)
  def find(user: User) = dao.find(clazz);
  def find() = dao.find(clazz)
  def merge(record: Record) = dao.merge(record);

  def parse(reader: BufferedReader): MutableList[Record] = {
    val list = new MutableList[Record]
    do {
      val line: String = reader.readLine
      if (!line) return list
      list += new Record(line)
      var i: Int = new Integer(line).toInt
    } while (true)
    return null
  }
  
  def toRecordAll(relations : List[Relation]) = {
    
  }
} 
开发者ID:writeonly,项目名称:babel,代码行数:36,代码来源:RecordBean.scala


示例14: 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


示例15: process

//设置package包名称以及导入依赖的类
package lert.core.rule

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

import lert.core.rule.target.TargetHelper
import groovy.lang.{Binding, GroovyShell}
import org.codehaus.groovy.control.CompilerConfiguration
import org.codehaus.groovy.control.customizers.ImportCustomizer

trait RuleRunner {
  def process(script: InputStream)
}

class GroovyRuleRunner extends RuleRunner {
  override def process(script: InputStream): Unit = {
    val bindings = new Binding() {
      //setVariable("message", JavaUtils.toJava(mes.data))
    }
    val importCustomizer = new ImportCustomizer()
    importCustomizer.addStaticStars(classOf[TargetHelper].getName)

    val config = new CompilerConfiguration() {
      addCompilationCustomizers(importCustomizer)
    }

    val shell = new GroovyShell(this.getClass.getClassLoader, bindings, config)
    shell.evaluate(new BufferedReader(new InputStreamReader(script)))
  }
} 
开发者ID:l3rt,项目名称:l3rt,代码行数:30,代码来源:RuleProcessor.scala


示例16: Yahoo

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

import java.io.{BufferedReader, InputStreamReader}
import java.time.LocalDate

import com.twitter.bijection.Conversion.asMethod
import com.twitter.finagle.http.Response
import com.twitter.finagle.service.{Backoff, RetryBudget}
import com.twitter.finagle.{Http, http}
import com.twitter.util.TimeConversions._
import com.twitter.util.{Await, Future}

import scala.collection.immutable.Seq

object Yahoo {


  private def rootUri = "real-chart.finance.yahoo.com"

  def pricesURL(businessDate : java.time.LocalDate, ticker: String) : String = {
    val lastYear = businessDate.minusYears(1)
    val url =f"http://$rootUri/table.csv?s=$ticker&a=${lastYear.getMonthValue}&b=${lastYear.getDayOfMonth}&c=${lastYear.getYear}&d=${businessDate.getMonthValue}&e=${businessDate.getDayOfMonth}&f=${businessDate.getYear}&g=d&ignore=.csv"
    url
  }

  private val budget: RetryBudget = RetryBudget(
    ttl = 10.seconds,
    minRetriesPerSec = 5,
    percentCanRetry = 0.1
  )

  private val client = Http.client
    .withRetryBudget(budget)
    .withRetryBackoff(Backoff.const(10 seconds))
    .newService(s"$rootUri:80")

  implicit val priceSource = new PriceSource[StockPrice] {
    override def fetchPrices(ticker: String) : Seq[StockPrice]  = {
      val request = http.Request(http.Method.Get, pricesURL(LocalDate.now, ticker))
      request.host = rootUri
      val response = client(request).as[Future[Response]]
      Await.result(response map { res =>
        val reader = new BufferedReader(new InputStreamReader(res.getInputStream))
        reader.readLine()
        Stream.continually(reader.readLine())
          .takeWhile(s=> s!= null && !s.isEmpty)
          .map { StockPrice(ticker, _) }
      })
    }
  }
} 
开发者ID:ashic,项目名称:scalaStocks,代码行数:52,代码来源:Yahoo.scala


示例17: getMessage

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

import java.io.{BufferedReader, IOException}

import scala.util.control.Breaks._
import scala.trace._


  def getMessage(bfReader: BufferedReader): Array[String] = {
    require(bfReader != null)
    var messageRows: Array[String] = Array[String]()
    try {
      breakable {
        while (true) {
          val nextLine = bfReader.readLine()
          // nextLine.trace
          //System.err.println("bf " + bfReader1.toString + " reading: " + nextLine)
          if (nextLine == null) {
            break // break out of loop if the end of the stream has been reached
          }
          else {
            messageRows = messageRows :+ nextLine // append the next line to the end
          }
        }
      }
    } catch {
      case ioe: IOException => // Don't worry about it.
    }
    messageRows
  }
} 
开发者ID:JohnReedLOL,项目名称:scala-trace-debug,代码行数:32,代码来源:TestingUtils.scala


示例18: BufferedReaderIterator

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

import java.io.{BufferedReader, FileInputStream, InputStreamReader}
import java.util.zip.GZIPInputStream



class BufferedReaderIterator(reader: BufferedReader) extends Iterator[String] {
  override def hasNext() = reader.ready
  override def next() = reader.readLine()
}
object GzFileIterator {
  def apply(file: java.io.File, encoding: String) = {
    new BufferedReaderIterator(
      new BufferedReader(
        new InputStreamReader(
          new GZIPInputStream(
            new FileInputStream(file)), encoding)))
  }
} 
开发者ID:bkstha,项目名称:my-log-api,代码行数:21,代码来源:GzFileIterator.scala


示例19: 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


示例20: 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



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Scala JsObject类代码示例发布时间:2022-05-23
下一篇:
Scala Path类代码示例发布时间: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