本文整理汇总了Scala中java.io.InputStreamReader类的典型用法代码示例。如果您正苦于以下问题:Scala InputStreamReader类的具体用法?Scala InputStreamReader怎么用?Scala InputStreamReader使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了InputStreamReader类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: parse
//设置package包名称以及导入依赖的类
package parsers
import java.io.{InputStream, InputStreamReader}
import java.nio.charset.StandardCharsets
import java.nio.file.{Files, Path, Paths}
import javax.script.ScriptEngineManager
import com.google.common.base.Charsets
import com.google.common.io.CharStreams
import org.luaj.vm2.{LuaTable, LuaValue}
import scala.collection.breakOut
import scala.io.Source
trait FactorioParser[T] {
import FactorioParser._
def parse(path: String): Seq[T] = commonParse(readAll(path))
def parse(path: Path): Seq[T] = commonParse(readAll(path))
def parse(is: InputStream): Seq[T] = {
val str = CharStreams.toString(new InputStreamReader(is, Charsets.UTF_8))
commonParse(str)
}
def transport(table: LuaTable): Option[T]
private[this] def commonParse(target: String): Seq[T] = {
val dataLua = Source.fromURL(getClass.getResource("/data.lua")).mkString
val lua = dataLua + target
val engine = manager.getEngineByName("luaj")
engine.eval(lua)
val array: LuaTable = engine.get("array").asInstanceOf[LuaTable]
tableToSeq(array)(_.checktable()).flatMap(transport)
}
}
object FactorioParser {
private val manager = new ScriptEngineManager()
def readAll(path: String): String = readAll(Paths.get(path))
def readAll(path: Path): String =
new String(Files.readAllBytes(path), StandardCharsets.UTF_8)
def tableToSeq[T](table: LuaTable)(f: LuaValue => T): Seq[T] = {
table.keys().map(table.get).map(f)(breakOut)
}
def tableToMap[K, V](table: LuaTable)(f: LuaValue => K)(g: LuaValue => V): Map[K, V] = {
table.keys().map { key =>
f(key) -> g(table.get(key))
}(breakOut)
}
}
示例2: 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)
}
}
}
}
示例3: Jade4jCompiler
//设置package包名称以及导入依赖的类
package com.karasiq.scalajsbundler.compilers
import java.io.InputStreamReader
import com.karasiq.scalajsbundler.ScalaJSBundler.{FileAsset, PageTypedContent}
import de.neuland.jade4j.Jade4J
import org.apache.commons.io.IOUtils
import scala.collection.JavaConversions._
import scala.util.control.Exception
class Jade4jCompiler extends AssetCompiler {
override def compile(contents: Seq[PageTypedContent]): String = {
val compiled = contents.map(_.asset match {
case FileAsset(file) ?
Jade4J.render(file, Map.empty[String, AnyRef], false)
case a ?
val reader = new InputStreamReader(a.content(), "UTF-8")
Exception.allCatch.andFinally(IOUtils.closeQuietly(reader)) {
Jade4J.render(reader, "input.jade", Map.empty[String, AnyRef], false)
}
})
HtmlConcatCompiler.concat(compiled)
}
}
示例4: CaseInsensitiveInputStream
//设置package包名称以及导入依赖的类
package io.github.nawforce.apexlink.utils
import java.io.{InputStream, InputStreamReader, Reader}
import org.antlr.v4.runtime.{ANTLRInputStream, IntStream}
class CaseInsensitiveInputStream(r: Reader, initialSize: Int, readChunkSize: Int)
extends ANTLRInputStream(r, initialSize, readChunkSize) {
//lazy is important here because need initiated data[], which is loaded in super class
private lazy val lowercaseData: Array[Char] = data.map(_.toLower)
def this(r: Reader) {
this(r, initialSize = 1024, readChunkSize = 1024)
}
def this(input: InputStream) {
this(new InputStreamReader(input), initialSize = 1024, readChunkSize = 1024)
}
override def LA(index: Int): Int = {
var i = index
if (i == 0) {
return 0
}
if (i < 0) {
i += 1
if ((p + i - 1) < 0) {
return IntStream.EOF
}
}
if ((p + i - 1) >= n) {
return IntStream.EOF
}
if (null != lowercaseData) {
lowercaseData(p + i - 1)
} else {
data(p + i - 1).toLower
}
}
def dump(): Unit = {
var i = 0
var value = 0
do {
value = LA(i)
i += 1
print(value.asInstanceOf[Char])
} while (value != IntStream.EOF)
}
}
示例5: 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)
示例6: Lambda
//设置package包名称以及导入依赖的类
package com.ovoenergy.lambda
import java.io.{Closeable, InputStreamReader}
import java.util.{Map => JMap}
import collection.JavaConverters._
import com.amazonaws.services.lambda.runtime.{Context, RequestHandler}
import com.amazonaws.services.s3.AmazonS3Client
import com.ovoenergy.lambda.client.{KafkaMetricsClient, LibratoClient}
import com.ovoenergy.lambda.domain.{ConsumerGroupMetricResponse, KafkaMetrics, PartitionData}
import com.squareup.okhttp.OkHttpClient
import com.typesafe.config.ConfigFactory
class Lambda extends RequestHandler[JMap[String, Object], Unit] with ConnectionHelpers{
val s3Client = new AmazonS3Client
override def handleRequest(event: JMap[String, Object], context: Context): Unit = {
val environment = context.getFunctionName.split('-').last
println(s"Hello, I'm a Lambda running in the $environment environment")
val config = using(s3Client.getObject("ovo-comms-platform-config", s"comms-burrow-polling-lambda/$environment/application.conf")){ s3Obj =>
using(new InputStreamReader(s3Obj.getObjectContent)){ configReader =>
ConfigFactory.parseReader(configReader)
}
}
val libratoEmail = config.getString("librato.api.email")
val libratoToken = config.getString("librato.api.token")
val libratoUrl = config.getString("librato.api.url")
val kafkaMetricsUrl = config.getString("kafka.metrics.url")
val kafkaConsumerGroups = config.getStringList("kafka.metrics.consumerGroups").asScala
val httpClient = new OkHttpClient()
val metricsClient = new KafkaMetricsClient(kafkaMetricsUrl, "local", kafkaConsumerGroups, httpClient)
val metrics = metricsClient.getMetrics.map(genKafkaMetrics)
using(new LibratoClient(libratoEmail, libratoToken, libratoUrl, environment)){ libratoClient =>
metrics.foreach { metric =>
libratoClient.addMetrics(metric)
}
libratoClient.submitMetrics()
}
}
private def genKafkaMetrics(response :ConsumerGroupMetricResponse): KafkaMetrics = {
val partitionData = response.status.partitions.map { partition =>
PartitionData(partition.partition, partition.end.lag)
}
KafkaMetrics(response.status.group, partitionData)
}
}
示例7: 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)
}
}
示例8: 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())
}
}
示例9: 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)
}
}
示例10: Img2TxtProcessor
//设置package包名称以及导入依赖的类
package pl.mojepanstwo.sap.toakoma.processors
import java.io.{File, FileInputStream, InputStreamReader}
import org.springframework.batch.item.ItemProcessor
import pl.mojepanstwo.sap.toakoma._
import scala.xml.{Elem, Node, XML}
import scala.xml.transform.RewriteRule
import sys.process._
class Img2TxtProcessor extends ItemProcessor[Model, Model] {
override def process(item:Model): Model = {
item.linksHtml.foreach { case (key, dirPath) =>
try {
val xml = XML.load(new InputStreamReader(new FileInputStream(item.xmlPath(key)), "UTF-8"))
val changed = new RewriteRule {
override def transform(n: Node): Seq[Node] = n match {
case elem @ Elem(_, "img", _, _, child @ _*) => {
val src = elem.attribute("src").get
val imageFile = new File(dirPath + "/" + src)
val cmd = "tesseract " +
imageFile.getAbsolutePath + " " +
"stdout " +
"-l pol"
var result = cmd !!
if(Option(result).exists(_.trim.isEmpty)) return n
result = result.replaceAll("-\n", "")
result = result.replaceAll("—\n", "")
return(<textFromImg>{result}</textFromImg>)
}
case elem: Elem => elem copy (child = elem.child flatMap (this transform))
case other => other
}
} transform xml
XML.save(dirPath + "/text_from_image.xml", changed(0), "UTF-8", true)
item.xmlPath(key) = dirPath + "/text_from_image.xml"
} catch {
case e: Throwable => println(e.printStackTrace())
}
}
item
}
}
示例11: 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 = {}
}
示例12: 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)))
}
}
示例13: Util
//设置package包名称以及导入依赖的类
package trap.xml
//import java.io.BufferedInputStream
//import java.io.BufferedOutputStream
//import java.io.BufferedReader
//import java.io.File
import java.io.FileInputStream
import java.io.InputStreamReader
import scala.xml.Elem
import scala.xml.Attribute
import scala.xml.Text
import scala.xml.Node
import scala.xml.NodeSeq
import scala.xml.Null
import scala.xml.PrettyPrinter
import scala.xml.XML
import trap.Util._
import trap.file.Util._
object Util {
def formatNicely(xmlFile:String) =
writeToTextFile(xmlFile, new PrettyPrinter(200, 2).format(loadXML(xmlFile)))
def formatNicely(xml:Elem) = new PrettyPrinter(200, 2).format(xml)
def getAttributeText(xml:NodeSeq, attrName:String) = {
printdbg (" ===> getAttributeTest "+xml+": "+attrName)
(xml \ ("@"+attrName)).text
}
private val r = <root/>
def getNode(n:String) = r.copy(label=n)
def addChild(n: Node, newChild: Node) = n match {
case Elem(prefix, label, attribs, scope, child @ _*) =>
Elem(prefix, label, attribs, scope, child ++ newChild : _*)
case _ => throw new Exception("Can only add children to elements!")
}
def addChildren(n:Node, children:NodeSeq) = children.foldLeft(n)((x, y) => addChild(x, y))
def addAttribute(n:Elem, attrName:String, attrValue:String) = n % Attribute(None, attrName, Text(attrValue), Null)
def attr(xml:Node, attrName:String) = (xml \ ("@"+attrName)).text
def loadXML(fileName:String) =
using(new FileInputStream(fileName)){
fis => using(new InputStreamReader(fis)){
isr => XML.load(isr)
}
}
def getElementName (x:Node) = x.nameToString(new StringBuilder).toString
def filterByAttr(xml:NodeSeq, attrName:String, attrValue:String) =
xml.filter(x => (x \ ("@"+attrName)).text == attrValue)
def getElementsWithAttribute(xml:NodeSeq, elementName:String, attrName:String, attrVal:String) =
xml \ elementName collect { x => (x \ ("@"+attrName)).map(_.text).contains(attrVal) match {
case true => x
}
}
def getElementWithAttribute(xml:NodeSeq, elementName:String, attrName:String, attrVal:String) =
((xml \ elementName).find{ x => (x \ ("@"+attrName)).map(_.text).contains(attrVal) }).get
def getChildren(xml:NodeSeq) = xml \ "_"
}
示例14: 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, _) }
})
}
}
}
示例15: UTF8Control
//设置package包名称以及导入依赖的类
package org.jmotor.i18n.control
import java.io.InputStreamReader
import java.net.{URL, URLConnection}
import java.util.ResourceBundle.Control
import java.util.{Locale, PropertyResourceBundle, ResourceBundle}
class UTF8Control(suffix: String = "properties") extends Control {
override def newBundle(baseName: String, locale: Locale, format: String, loader: ClassLoader, reload: Boolean): ResourceBundle = {
// The below is a copy of the default implementation.
val bundleName = toBundleName(baseName, locale)
val resourceName = toResourceName(bundleName, suffix)
val stream = if (reload) {
for {
url: URL ? Option(loader.getResource(resourceName))
connection: URLConnection ? Option(url.openConnection())
} yield {
connection.setUseCaches(false)
connection.getInputStream
}
} else {
Option(loader.getResourceAsStream(resourceName))
}
(for {
_stream ? stream
} yield {
new PropertyResourceBundle(new InputStreamReader(_stream, "UTF-8"))
}).orNull
}
}