本文整理汇总了Scala中java.io.BufferedReader类的典型用法代码示例。如果您正苦于以下问题:Scala BufferedReader类的具体用法?Scala BufferedReader怎么用?Scala BufferedReader使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了BufferedReader类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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)
}
}
}
}
示例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)
}
示例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)
示例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")
}
}
示例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)
}
}
示例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())
}
}
示例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)
}
}
示例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")
})
}
)
}
}
示例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")
})
}
)
}
}
示例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
}
示例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 = {}
}
示例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]) = {
}
}
示例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})
}
}
示例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)))
}
}