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

Scala InputStreamReader类代码示例

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

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



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


} 
开发者ID:ponkotuy,项目名称:FactorioRecipe,代码行数:57,代码来源:FactorioParser.scala


示例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)
      }
    }
  }
} 
开发者ID:vincenzobaz,项目名称:Parallelism-and-Concurrency-Assignments,代码行数:46,代码来源:CommandReader.scala


示例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)
  }
} 
开发者ID:Karasiq,项目名称:sbt-scalajs-bundler,代码行数:28,代码来源:Jade4jCompiler.scala


示例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)
  }
} 
开发者ID:nawforce,项目名称:ApexLink,代码行数:55,代码来源:CaseInsensitiveInputStream.scala


示例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) 
开发者ID:romanarranz,项目名称:NTP,代码行数:20,代码来源:excepcionesTryCatchFinally.scala


示例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)
  }
} 
开发者ID:ovotech,项目名称:comms-burrow-polling-lambda,代码行数:52,代码来源:Lambda.scala


示例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)
  }
} 
开发者ID:virdis,项目名称:ddl-concordance,代码行数:50,代码来源:DDApp.scala


示例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())
  }
} 
开发者ID:arguslab,项目名称:Argus-SAF,代码行数:45,代码来源:JVMUtil.scala


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

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


示例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
  }
} 
开发者ID:PrawoPolskie,项目名称:toakoma,代码行数:56,代码来源:Img2TxtProcessor.scala


示例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 = {}
} 
开发者ID:jspam,项目名称:mjis,代码行数:28,代码来源:GccRunner.scala


示例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)))
  }
} 
开发者ID:l3rt,项目名称:l3rt,代码行数:30,代码来源:RuleProcessor.scala


示例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 \ "_"
} 
开发者ID:scalahub,项目名称:acc,代码行数:60,代码来源:Util.scala


示例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, _) }
      })
    }
  }
} 
开发者ID:ashic,项目名称:scalaStocks,代码行数:52,代码来源:Yahoo.scala


示例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
  }
} 
开发者ID:aiyanbo,项目名称:scala-i18n,代码行数:35,代码来源:UTF8Control.scala


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


示例17: MnemonicCodeSpec

//设置package包名称以及导入依赖的类
package fr.acinq.syscoin

import java.io.InputStreamReader

import org.json4s.DefaultFormats
import org.json4s.jackson.JsonMethods
import org.junit.runner.RunWith
import org.scalatest.FlatSpec
import org.scalatest.junit.JUnitRunner

object MnemonicCodeSpec {

  case class TestVectors(english: Array[Array[String]])

}

@RunWith(classOf[JUnitRunner])
class MnemonicCodeSpec extends FlatSpec {

  import MnemonicCode._
  import MnemonicCodeSpec._

  "MnemonicCode" should "pass reference tests" in {
    implicit val format = DefaultFormats

    val stream = classOf[MnemonicCodeSpec].getResourceAsStream("/bip39_vectors.json")
    val vectors = JsonMethods.parse(new InputStreamReader(stream)).extract[TestVectors]
    vectors.english.map(_ match {
      case Array(raw, mnemonics, seed) =>
        assert(toMnemonics(BinaryData(raw)).mkString(" ") === mnemonics)
        assert(toSeed(toMnemonics(BinaryData(raw)), "TREZOR") === BinaryData(seed))
    })
  }
} 
开发者ID:sidhujag,项目名称:syscoin-lib,代码行数:35,代码来源:MnemonicCodeSpec.scala


示例18: SighashSpec

//设置package包名称以及导入依赖的类
package fr.acinq.syscoin.reference

import java.io.InputStreamReader

import fr.acinq.syscoin._
import org.json4s.DefaultFormats
import org.json4s.JsonAST.{JInt, JString, JValue}
import org.json4s.jackson.JsonMethods
import org.junit.runner.RunWith
import org.scalatest.FlatSpec
import org.scalatest.junit.JUnitRunner

@RunWith(classOf[JUnitRunner])
class SighashSpec extends FlatSpec {
  implicit val format = DefaultFormats

  "syscoin-lib" should "pass reference client sighash tests" in {
    val stream = classOf[Base58Spec].getResourceAsStream("/data/sighash.json")
    val json = JsonMethods.parse(new InputStreamReader(stream))
    // use tail to skip the first line of the .json file
    json.extract[List[List[JValue]]].tail.map(_ match {
      case JString(raw_transaction) :: JString(script) :: JInt(input_index) :: JInt(hashType) :: JString(signature_hash) :: Nil => {
        val tx = Transaction.read(raw_transaction)
        val hash = Transaction.hashForSigning(tx, input_index.intValue, fromHexString(script), hashType.intValue)
        assert(toHexString(hash.reverse) === signature_hash)
      }
      case _ => println("warning: could not parse sighash.json properly!")
    })
  }
} 
开发者ID:sidhujag,项目名称:syscoin-lib,代码行数:31,代码来源:SighashSpec.scala


示例19: amiId

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

import java.io.{BufferedReader, InputStreamReader}
import java.net.{HttpURLConnection, URL}

import scala.collection.JavaConverters._

trait Accessor {
  private val base = "http://169.254.169.254/latest/meta-data/"
  def amiId: String = doRequest("ami-id")
  def hostName: String = doRequest("hostname")
  def instanceId: String = doRequest("instance-id")
  def instanceType: String = doRequest("instance-type")
  def localHostName: String = doRequest("local-hostname")
  def localIpv4: String = doRequest("local-ipv4")
  def publicHostName: String = doRequest("public-hostname")
  def publicIpv4: String = doRequest("public-ipv4")
  private def doRequest(url: URL): String = {
    val conn = url.openConnection().asInstanceOf[HttpURLConnection]
    conn.setRequestMethod("GET")
    conn.connect()
    new BufferedReader(new InputStreamReader(conn.getInputStream))
      .lines()
      .iterator()
      .asScala
      .mkString("\n")
  }
  private def doRequest(url: String): String = doRequest(new URL(base + url))
}
object Accessor extends Accessor 
开发者ID:yuiwai,项目名称:ec2-metadata,代码行数:31,代码来源:Accessor.scala


示例20: QueryGeneratorTest

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

import io.circe._
import io.circe.generic.auto._
import io.circe.parser._
import io.circe.syntax._
import io.circe.yaml.parser
import java.io.InputStreamReader
import scala.collection.JavaConverters._
import org.apache.jena.query.QueryFactory

class QueryGeneratorTest extends UnitSpec {

  "Defined class" should "be first column" in {
    val dosdp = (for {
      json <- parser.parse(new InputStreamReader(getClass.getResourceAsStream("QueryGeneratorTest.yaml"))).right.toOption
      pattern <- json.as[DOSDP].right.toOption
    } yield pattern).getOrElse(???)
    val prefixes = (for {
      prefixesJson <- parser.parse(new InputStreamReader(getClass.getResourceAsStream("StandardPrefixes.yaml"))).right.toOption
      prefixMap <- prefixesJson.as[Map[String, String]].right.toOption
    } yield prefixMap).getOrElse(Map.empty)
    val variables = QueryFactory.create(SPARQL.queryFor(ExpandedDOSDP(dosdp, prefixes))).getProjectVars.asScala
    variables(0).getVarName shouldEqual "defined_class"
    variables(1).getVarName shouldEqual "defined_class_label"
  }

} 
开发者ID:INCATools,项目名称:dosdp-tools,代码行数:29,代码来源:QueryGeneratorTest.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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