当前位置: 首页>>代码示例>>Scala>>正文


Scala OutputStream类代码示例

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


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

示例1: Codec

//设置package包名称以及导入依赖的类
package at.hazm.quebic

import java.io.{ByteArrayInputStream, ByteArrayOutputStream, InputStream, OutputStream}
import java.util.zip.{GZIPInputStream, GZIPOutputStream}

import scala.annotation.tailrec

sealed abstract class Codec(val id:Byte, val name:String) extends Type {
  def encode(buffer:Array[Byte]):Array[Byte]

  def decode(buffer:Array[Byte]):Array[Byte]
}

object Codec {
  val values:Seq[Codec] = Seq(PLAIN, GZIP)
  private[this] val valuesMap = values.groupBy(_.id).mapValues(_.head)

  def valueOf(id:Byte):Codec = valuesMap(id)

  case object PLAIN extends Codec(0, "plain") {
    def encode(buffer:Array[Byte]):Array[Byte] = buffer

    def decode(buffer:Array[Byte]):Array[Byte] = buffer
  }

  case object GZIP extends Codec(1, "gzip") {
    def encode(buffer:Array[Byte]):Array[Byte] = {
      val baos = new ByteArrayOutputStream()
      val out = new GZIPOutputStream(baos)
      out.write(buffer)
      out.finish()
      out.finish()
      baos.toByteArray
    }

    def decode(buffer:Array[Byte]):Array[Byte] = {
      val in = new GZIPInputStream(new ByteArrayInputStream(buffer))
      val out = new ByteArrayOutputStream()
      _copy(in, out, new Array[Byte](2014))
      out.close()
      out.toByteArray
    }
  }

  @tailrec
  private[Codec] def _copy(in:InputStream, out:OutputStream, buffer:Array[Byte]):Unit = {
    val len = in.read(buffer)
    if(len > 0) {
      out.write(buffer, 0, len)
      _copy(in, out, buffer)
    }
  }

} 
开发者ID:torao,项目名称:quebic,代码行数:55,代码来源:Codec.scala

示例2: OutputStreamLoggerAdapter

//设置package包名称以及导入依赖的类
package logoon.adapters.console

import java.io.{ OutputStream, PrintStream }

import logoon._

class OutputStreamLoggerAdapter(output: OutputStream) extends LoggerAdapter {
  override def log(name: String, level: LogLevel, message: => String, context: Map[String, String]): Unit = {
    output.write("[%-5s] %s\n".format(level, message).getBytes())
    context.foreach { case (key, value) => output.write("%25s = %s\n".format(key, value).getBytes) }
  }
  override def log(name: String, level: LogLevel, message: => String, throwable: => Throwable, context: Map[String, String]): Unit = {
    log(name, level, message, context)
    throwable.printStackTrace(new PrintStream(output))
  }
}

object ConsoleLoggerAdapter extends OutputStreamLoggerAdapter(System.out)

class InMemoryLogLevelConfig extends LogLevelConfig {
  var levels: Map[String, LogLevel] = Map("" -> LogLevel.OFF)
  override def logLevel(name: String): LogLevel =
    levels.get(name) match {
      case Some(level) => level
      case None        => logLevel(name.substring(0, name.length - 1))
    }
  override def setLogLevel(name: String, level: LogLevel): Unit = levels += (name -> level)
} 
开发者ID:btlines,项目名称:logoon,代码行数:29,代码来源:ConsoleLoggerAdapter.scala

示例3: PdfEbook

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

import java.io.{File, OutputStream}

import com.transgee.ebook.{Ebook, Metadata}
import org.apache.pdfbox.pdmodel.PDDocument
import org.apache.pdfbox.rendering.PDFRenderer
import org.apache.pdfbox.tools.imageio.ImageIOUtil

class PdfEbook(doc: PDDocument) extends Ebook {
  def toc() = {
    new TocExtractor(doc).extract()
  }

  def figures() = new FigureIterator(doc)

  def metadata() = {
    val info = doc.getDocumentInformation
    Metadata(info.getTitle, info.getAuthor, doc.getNumberOfPages)
  }

  def cover[O <: OutputStream](to: O): O = try {
    val info = doc.getDocumentInformation
    val renderer = new PDFRenderer(doc)
    val image = renderer.renderImage(0)
    ImageIOUtil.writeImage(image, "png", to)
    to
  } finally {
    to.close()
  }

  def close() = doc.close()
}

object PdfEbook {
  def apply(filePath: String) = {
    new PdfEbook(PDDocument.load(new File(filePath)))
  }
} 
开发者ID:zenkiezhu,项目名称:scala-ebook-clipper,代码行数:40,代码来源:PdfEbook.scala

示例4: Barcoder

//设置package包名称以及导入依赖的类
package kokellab.utils.misc

import java.io.{FileOutputStream, OutputStream, FileInputStream}
import java.nio.file.Path
import javax.imageio.ImageIO

import com.google.zxing.client.j2se.{MatrixToImageWriter, BufferedImageLuminanceSource}
import com.google.zxing.common.HybridBinarizer
import com.google.zxing.BinaryBitmap
import com.google.zxing._

class Barcoder(val barcodeFormat: BarcodeFormat, val imageFormat: String, val width: Int, val height: Int) {

	def decode(path: Path): String = {
		val stream = new FileInputStream(path.toFile)
		try {
			decode(stream)
		} finally stream.close()
	}

	def decode(stream: java.io.InputStream): String = {
		val bitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(ImageIO.read(stream))))
		new MultiFormatReader().decode(bitmap).getText
	}

	def encode(text: String, path: Path) {
		encode(text, new FileOutputStream(path.toFile))
	}

	def encode(text: String, stream: OutputStream) = {
		val matrix = new MultiFormatWriter().encode(text, barcodeFormat, width, height, null)
		MatrixToImageWriter.writeToStream(matrix, imageFormat, stream)
	}

} 
开发者ID:kokellab,项目名称:kl-common-scala,代码行数:36,代码来源:Barcoder.scala

示例5: IntPrinter

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

import scala.Console._



class IntPrinter(stream: OutputStream) {
  def printSequenceUsingForLoop(sequence: Seq[Int]) = {
    Console.setOut(stream)
    for (element <- sequence) print(element)
  }

  def printSequenceUsingPartiallyAppliedFunctionInForeach(sequence: Seq[Int]) = {
    Console setOut (stream)
    sequence.foreach(print)
  }


  def printSequenceUsingFunctionLiteralInForeach(sequence: Seq[Int]) = {
    Console.setOut(stream)
    sequence.foreach(s => print(s))
  }

  def printSequenceUsingWhileLoop(sequence: Seq[Int]) = {
    Console.setOut(stream)
    var index = 0
    while (index < sequence.size) {
      val tmp = sequence(index)
      print(sequence(index) toString)
      index += 1
    }
  }
} 
开发者ID:szymonlyszkowski,项目名称:learning-scala,代码行数:34,代码来源:IntPrinter.scala

示例6: ZipUtil

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

import java.io.{File, FileOutputStream, InputStream, OutputStream}
import java.util.zip.{ZipEntry, ZipFile}

import scala.collection.JavaConverters._


object ZipUtil {
  val BUFSIZE = 4096
  val buffer = new Array[Byte](BUFSIZE)

  def unZip(source: String, targetFolder: String): Boolean = {
    val zipFile = new ZipFile(source)

    unzipAllFile(zipFile.entries.asScala.toList, getZipEntryInputStream(zipFile), new File(targetFolder))
  }

  def getZipEntryInputStream(zipFile: ZipFile)(entry: ZipEntry): InputStream = zipFile.getInputStream(entry)

  def unzipAllFile(entryList: List[ZipEntry], inputGetter: (ZipEntry) => InputStream, targetFolder: File): Boolean = {

    entryList match {
      case entry :: entries =>

        if (entry.isDirectory)
          new File(targetFolder, entry.getName).mkdirs
        else
          saveFile(inputGetter(entry), new FileOutputStream(new File(targetFolder, entry.getName)))

        unzipAllFile(entries, inputGetter, targetFolder)
      case _ =>
        true
    }

  }

  def saveFile(fis: InputStream, fos: OutputStream): Unit = {
    writeToFile(bufferReader(fis), fos)
    fis.close()
    fos.close()
  }

  def bufferReader(fis: InputStream)(buffer: Array[Byte]): (Int, Array[Byte]) = (fis.read(buffer), buffer)

  def writeToFile(reader: (Array[Byte]) => ((Int, Array[Byte])), fos: OutputStream): Boolean = {
    val (length, data) = reader(buffer)
    if (length >= 0) {
      fos.write(data, 0, length)
      writeToFile(reader, fos)
    } else
      true
  }
} 
开发者ID:arguslab,项目名称:Argus-SAF,代码行数:55,代码来源:ZipUtil.scala

示例7: extract

//设置package包名称以及导入依赖的类
package com.github.jodersky.flow
package internal

import java.io.{ File, FileOutputStream, InputStream, OutputStream }


  private def extract(path: String, prefix: String): Option[File] = {
    var in: Option[InputStream] = None
    var out: Option[OutputStream] = None

    try {
      in = Option(NativeLoader.getClass.getResourceAsStream(path))
      if (in.isEmpty) return None

      val file = File.createTempFile(prefix, "")
      out = Some(new FileOutputStream(file))

      val buffer = new Array[Byte](BufferSize)
      var length = -1;
      do {
        length = in.get.read(buffer)
        if (length != -1) out.get.write(buffer, 0, length)
      } while (length != -1)

      Some(file)
    } finally {
      in.foreach(_.close)
      out.foreach(_.close)
    }
  }

  private def loadFromJar(library: String) = {
    val fqlib = System.mapLibraryName(library) //fully qualified library name
    val path = s"/native/${os}-${arch}/${fqlib}"
    extract(path, fqlib) match {
      case Some(file) => System.load(file.getAbsolutePath)
      case None => throw new UnsatisfiedLinkError("Cannot extract flow's native library, " +
        "the native library does not exist for your specific architecture/OS combination." +
        "Could not find " + path + ".")
    }
  }

  def load(library: String) = try {
    System.loadLibrary(library)
  } catch {
    case ex: UnsatisfiedLinkError => loadFromJar(library)
  }

} 
开发者ID:csarnevesht,项目名称:flow-serial,代码行数:50,代码来源:NativeLoader.scala

示例8: OutputBuildProperties

//设置package包名称以及导入依赖的类
package com.github.madoc.create_sbt_project.model.output

import java.io.OutputStream

import com.github.madoc.create_sbt_project.io.{Output, Write}
import com.github.madoc.create_sbt_project.model.BuildProperties

object OutputBuildProperties extends Output[BuildProperties] {
  def apply(the:BuildProperties)(write:Write) {
    val p = new java.util.Properties
    (the sbtVersion) foreach {p setProperty("sbt.version", _)}
    val wr = write
    p.store(new OutputStream {
      var firstLineSkipped = false
      def write(b:Int) {
        if(firstLineSkipped) wr(b toChar) else if(b.toChar == '\n') firstLineSkipped=true
      }
    }, null)
  }
} 
开发者ID:Madoc,项目名称:create-sbt-project,代码行数:21,代码来源:OutputBuildProperties.scala

示例9: ScriptRunner

//设置package包名称以及导入依赖的类
package at.hazm.quebic

import java.io.{InputStream, OutputStream}

import org.slf4j.LoggerFactory

import scala.annotation.tailrec

object ScriptRunner {
  private[ScriptRunner] val logger = LoggerFactory.getLogger(getClass.getName.dropRight(1))

  def execJar(cmd:String, args:String*):Process = {
    val c = (Seq("java", "-jar", cmd) ++ args).toArray
    logger.info(c.mkString(" "))
    new ProcessBuilder()
      .command(c:_*)
      .inheritIO()
      .start()
  }

  def copy(in:InputStream, out:OutputStream):Long = {
    @tailrec
    def _copy(buffer:Array[Byte], length:Long = 0):Long = {
      val len = in.read(buffer)
      if(len < 0) length else {
        out.write(buffer, 0, len)
        out.flush()
        _copy(buffer, length + len)
      }
    }

    _copy(new Array[Byte](1024))
  }

} 
开发者ID:torao,项目名称:quebic,代码行数:36,代码来源:ScriptRunner.scala

示例10: IOUtils

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

import com.github.shadowsocks.utils.CloseUtils._
import java.io.{FileWriter, InputStream, OutputStream}


object IOUtils {
  private final val BUFFER_SIZE = 32 * 1024

  def copy(in: InputStream, out: OutputStream) {
    val buffer = new Array[Byte](BUFFER_SIZE)
    while (true) {
      val count = in.read(buffer)
      if (count >= 0) out.write(buffer, 0, count) else return
    }
  }

  def readString(in: InputStream): String = {
    val builder = new StringBuilder()
    val buffer = new Array[Byte](BUFFER_SIZE)
    while (true) {
      val count = in.read(buffer)
      if (count >= 0) builder.append(new String(buffer, 0, count)) else return builder.toString()
    }
    null
  }

  def writeString(file: String, content: String) = autoClose(new FileWriter(file))(writer => writer.write(content))
} 
开发者ID:RoomArchitect,项目名称:test0000,代码行数:30,代码来源:IOUtils.scala

示例11: GZipServletOutputStream

//设置package包名称以及导入依赖的类
package co.informatica.mvc.filters

import java.io.{IOException, OutputStream}
import java.util.zip.GZIPOutputStream
import javax.servlet.{ServletOutputStream, WriteListener}

class GZipServletOutputStream @throws[IOException]
(val output: OutputStream) extends ServletOutputStream {
  private val gzipOutputStream = new GZIPOutputStream(output)

  @throws[IOException]
  override def close(): Unit = {
    this.gzipOutputStream.close()
  }

  @throws[IOException]
  override def flush(): Unit = {
    this.gzipOutputStream.flush()
  }

  @throws[IOException]
  override def write(b: Array[Byte]): Unit = {
    this.gzipOutputStream.write(b)
  }

  @throws[IOException]
  override def write(b: Array[Byte], off: Int, len: Int): Unit = {
    this.gzipOutputStream.write(b, off, len)
  }

  @throws[IOException]
  override def write(b: Int): Unit = {
    this.gzipOutputStream.write(b)
  }

  override def isReady: Boolean = ???

  override def setWriteListener(writeListener: WriteListener): Unit = {

  }
} 
开发者ID:jkevingutierrez,项目名称:MVC,代码行数:42,代码来源:GZipServletOutputStream.scala

示例12: Pkcs12Convertor

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

import java.io.{OutputStream, Reader}
import java.security.cert.X509Certificate
import java.security.{KeyStore, PrivateKey}

import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter
import org.bouncycastle.openssl.{PEMKeyPair, PEMParser}

object Pkcs12Convertor {

  def parsePrivateKey(reader: Reader): PrivateKey = {
    val pemParser = new PEMParser(reader)
    val pemKeyPair = pemParser.readObject().asInstanceOf[PEMKeyPair]
    new JcaPEMKeyConverter().getKeyPair(pemKeyPair).getPrivate
  }

  def parseCertificate(reader: Reader): X509Certificate = {
    val pemParser = new PEMParser(reader)
    val certificate = pemParser.readObject()
    null
  }

  def write(os: OutputStream, privateKey: PrivateKey, password: Array[Char], certificate: X509Certificate): Unit = {
    val keyStore = KeyStore.getInstance("pkcs12")
    keyStore.load(null, password)

    keyStore.setKeyEntry("1", privateKey, password, Seq(certificate).toArray)
    keyStore.store(os, password)
  }

} 
开发者ID:takesection,项目名称:apple-mdm-certificate,代码行数:33,代码来源:Pkcs12Convertor.scala

示例13: Main

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

import java.io.{ InputStream, OutputStream }
import java.net.URLDecoder

import com.fasterxml.jackson.databind.{ DeserializationFeature, ObjectMapper }
import com.fasterxml.jackson.module.scala.DefaultScalaModule

class Main {
  val scalaMapper = new ObjectMapper().registerModule(new DefaultScalaModule).configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)

  def handler(input: InputStream, output: OutputStream): Unit = {
    val params = scalaMapper.readValue(input, classOf[SlackOutgoingData])
    println(params)
    val result = params.decodedText match {
      case "?????" => Some(s"?????, ${params.user_name}")
      case "Scala"      => Some("?????")
      case _            => None
    }

    result.foreach { r =>
      output.write( s"""{ "text": "$r" }""".getBytes("UTF-8"))
    }
  }
}

case class SlackOutgoingData(
  token: String,
  team_id: String,
  team_domain: String,
  service_id: String,
  channel_id: String,
  channel_name: String,
  timestamp: String,
  user_id: String,
  user_name: String,
  text: String,
  trigger_word: String) {

  val decodedText = URLDecoder.decode(text, "UTF-8")

} 
开发者ID:SAMMY7th,项目名称:aws-lambda-scala,代码行数:43,代码来源:Main.scala

示例14: AddNew

//设置package包名称以及导入依赖的类
package codes.bytes.quaich.samples.plain

import java.io.OutputStream

import akka.typed.scaladsl.Actor
import akka.typed.scaladsl.AskPattern._
import akka.typed.{ActorRef, ActorSystem, Behavior}
import akka.util.Timeout
import codes.bytes.quaich.api.LambdaContext
import codes.bytes.quaich.api.direct.{DirectLambda, DirectLambdaHandler}
import org.json4s.JValue
import org.json4s.JsonAST.JString

import scala.concurrent.{Await, Future}
import scala.concurrent.duration._

sealed trait NameMsg

final case class AddNew(lang: String, replyTo: ActorRef[Array[String]]) extends NameMsg

@DirectLambda
class PlainLambda extends DirectLambdaHandler {
  implicit val timeout = Timeout(1.second)

  val namedBehavior: Behavior[NameMsg] = Actor.mutable[NameMsg](ctx => new NameActor)

  val system: ActorSystem[NameMsg] = ActorSystem("hello", namedBehavior)

  override protected def handleEvent(json: JValue, output: OutputStream)(implicit ctx: LambdaContext) {
    json match {
      case JString(lang) =>
        implicit val scheduler = system.scheduler
        val results: Future[Array[String]] = system ? { ref => AddNew(lang, ref) }
        writeJson (output, Await.result (results, timeout.duration) )

      case other =>
        ctx.log.error(s"Uncreckognized JSON format")
    }
  }
}

class NameActor extends Actor.MutableBehavior[NameMsg] {

  private var names: List[String] = Nil

  override def onMessage(msg: NameMsg): Behavior[NameMsg] = {
    msg match {
      case AddNew(lang, replyTo) =>
        names = lang :: names
        replyTo ! names.toArray
    }

    this
  }
} 
开发者ID:pdolega,项目名称:quaich-other-samples,代码行数:56,代码来源:AkkaLambda.scala

示例15: GpgFileGenerator

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

import com.gaiam.gcsis.util.EncryptedSignedOutputStream

import java.io.InputStream
import java.io.OutputStream

object GpgFileGenerator {
    def apply(
        delegate: FileGenerator,
        pubringFile: String,
        secringFile: String,
        partialEncryptionKeyId: String,
        partialSignatureKeyId: String,
        password: String
    ) = new GpgFileGenerator(
        delegate,
        EncryptedSignedOutputStream(_, fileName(delegate), pubringFile, secringFile, partialEncryptionKeyId, partialSignatureKeyId, password)
    )

    def apply(
        delegate: FileGenerator,
        publicKeyringStream: InputStream,
        secretKeyringStream: InputStream,
        partialEncryptionKeyId: String,
        partialSignatureKeyId: String,
        password: String
    ) = new GpgFileGenerator(
        delegate,
        EncryptedSignedOutputStream(_, fileName(delegate), publicKeyringStream, secretKeyringStream, partialEncryptionKeyId, partialSignatureKeyId, password)
    )

    def fileName(gen: FileGenerator) = gen.fileName + ".gpg"
}

class GpgFileGenerator private (delegate: FileGenerator, f: OutputStream => OutputStream) extends FileGenerator {
    def fileName = GpgFileGenerator.fileName(delegate)

    def write(os: OutputStream) = delegate.write(f(os))
} 
开发者ID:GaiamTV,项目名称:gcsi-scala-util,代码行数:41,代码来源:GpgFileGenerator.scala


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