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

Scala OutputStream类代码示例

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

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



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


示例16: ZipArchive

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

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

import scala.collection.JavaConversions._

//https://gist.github.com/Swind/2568527
class ZipArchive {

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

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

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

  def getZipEntryInputStream(zipFile: ZipFile)(entry: ZipEntry) = 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) = {
    writeToFile(bufferReader(fis) _, fos)
    fis.close
    fos.close
  }

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

  def writeToFile(reader: (Array[Byte]) => Tuple2[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:wongcyrus,项目名称:awslambdamavenbuild,代码行数:56,代码来源:ZipArchive.scala


示例17: NameInfo

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

import scala.collection.JavaConverters._
import java.net.URLDecoder
import java.io.{InputStream, OutputStream, PrintStream}
import com.amazonaws.services.lambda.runtime.events.S3Event

case class NameInfo(firstName: String, lastName: String)

case class MyLambdaApp() {
  def decodeS3Key(key: String): String = URLDecoder.decode(key.replace("+", " "), "utf-8")

  @LambdaFunction(path="/getsource", inputModel="I", outputModel="O")
  def getSourceBuckets(event: S3Event): java.util.List[String] = {
    val result = event.getRecords.asScala.map(record => decodeS3Key(record.getS3.getObject.getKey)).asJava
    println(result)
    return result
  }

  val scalaMapper = {
    import com.fasterxml.jackson.databind.ObjectMapper
    import com.fasterxml.jackson.module.scala.DefaultScalaModule
    new ObjectMapper().registerModule(new DefaultScalaModule)
  }

  @LambdaFunction(path="/greeting", inputModel="I", outputModel="O")
  def greeting(input: InputStream, output: OutputStream): Unit = {
    val name = scalaMapper.readValue(input, classOf[NameInfo])
    val result = s"Greetings ${name.firstName} ${name.lastName}." 
    output.write(result.getBytes("UTF-8"))
  }
} 
开发者ID:Java1Guy,项目名称:sbt-scalamkins,代码行数:33,代码来源:MyLambdaApp.scala


示例18: ConnectionServer

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

import annotation.tailrec

import java.io.InputStream
import java.io.ObjectInputStream
import java.io.ObjectOutputStream
import java.io.OutputStream

import java.net.ServerSocket
import java.net.Socket


object ConnectionServer extends App
{
  @tailrec
  final def handleConnection (server_socket : ServerSocket,
                              connection_stream_pair_list : List[((String, Int), ObjectOutputStream)]) : Unit =
  {
    val socket : Socket = server_socket.accept
    val input_stream : InputStream = socket.getInputStream
    val output_stream : OutputStream = socket.getOutputStream
    val object_input_stream : ObjectInputStream = new ObjectInputStream (input_stream)
    val object_output_stream : ObjectOutputStream = new ObjectOutputStream (output_stream)
    val received_object : Object = object_input_stream.readObject
    val received_connection_message : Connection = received_object.asInstanceOf[Connection]
    val received_connection : (String, Int) = received_connection_message.connection
    val connection_stream_pair : ((String, Int), ObjectOutputStream) = (received_connection, object_output_stream)
    connection_stream_pair_list.foreach
    {
      connection_stream_pair : ((String, Int), ObjectOutputStream) =>
      {
        val (_, object_output_stream : ObjectOutputStream) = connection_stream_pair
        object_output_stream.writeObject (received_connection_message)
      }
    }
    val connection_list : List[(String, Int)] = connection_stream_pair_list.map
    {
      connection_stream_pair : ((String, Int), ObjectOutputStream) =>
      {
        val (connection : (String, Int), _) = connection_stream_pair
        connection
      }
    }
    val connection_list_message : ConnectionList = ConnectionList (connection_list)
    object_output_stream.writeObject (connection_list_message)
    handleConnection (server_socket, connection_stream_pair :: connection_stream_pair_list)
  }

  val local_port : Int = args(0).toInt
  val server_socket : ServerSocket = new ServerSocket (local_port)
  val connection_stream_pair_list : List[((String, Int), ObjectOutputStream)] = Nil
  handleConnection (server_socket, connection_stream_pair_list)
} 
开发者ID:vdorbs,项目名称:Control-OS,代码行数:55,代码来源:Servers.scala


示例19: GpxWriter

//设置package包名称以及导入依赖的类
package com.pds.poi4s.gpx

import java.io.OutputStream

import com.pds.poi4s.gpx.GpxVersion._

import scala.xml.{Elem, PrettyPrinter}

object GpxWriter {
  private val prettyPrinter = new PrettyPrinter(80, 4)

  def write(gpxFile: GpxFile, os: OutputStream, version: GpxVersion = Version11): Unit = {
    val xml = version match {
      case Version10 => generateVersion10(gpxFile)
      case Version11 => generateVersion11(gpxFile)
    }

    os.write(prettyPrinter.format(xml).getBytes("UTF-8"))
  }

  private def generateVersion10(gpxFile: GpxFile): Elem = {
    <gpx version="1.0" creator="poi4s">
      {gpxFile.name.map(n => <name>{n}</name>).orNull}

      {
        gpxFile.waypoints map { wpt =>
          <wpt lat={wpt.lat.toString} lon={wpt.lon.toString}>
            {wpt.name.map(n => <name>{n}</name>).orNull}
            {wpt.elevation.map(e => <ele>{e}</ele>).orNull}
            {wpt.comment.map(c => <cmt>{c}</cmt>).orNull}
            {wpt.description.map(d => <desc>{d}</desc>).orNull}
            {wpt.link.map(l => <url>{l}</url>).orNull}
            {wpt.source.map(s => <src>{s}</src>).orNull}
          </wpt>
        }
      }
    </gpx>
  }

  private def generateVersion11(gpxFile: GpxFile): Elem = {
    <gpx version="1.1" creator="poi4s">
      <metadata>
        {gpxFile.name.map(n => <name>{n}</name>).orNull}
      </metadata>

      {
      gpxFile.waypoints map { wpt =>
        <wpt lat={wpt.lat.toString} lon={wpt.lon.toString}>
          {wpt.name.map(n => <name>{n}</name>).orNull}
          {wpt.elevation.map(e => <ele>{e}</ele>).orNull}
          {wpt.comment.map(c => <cmt>{c}</cmt>).orNull}
          {wpt.description.map(d => <desc>{d}</desc>).orNull}
          {wpt.link.map(l => <link>{l}</link>).orNull}
          {wpt.source.map(s => <src>{s}</src>).orNull}
        </wpt>
      }
      }
    </gpx>
  }
} 
开发者ID:stringbean,项目名称:poi4s,代码行数:61,代码来源:GpxWriter.scala


示例20: AvroWriter

//设置package包名称以及导入依赖的类
package io.eels.component.avro

import java.io.OutputStream
import java.util.concurrent.atomic.AtomicInteger

import io.eels.Row
import io.eels.schema.StructType
import org.apache.avro.file.DataFileWriter
import org.apache.avro.generic
import org.apache.avro.generic.GenericRecord

class AvroWriter(structType: StructType, out: OutputStream) {
  
  private val schema = AvroSchemaFns.toAvroSchema(structType)
  private val datumWriter = new generic.GenericDatumWriter[GenericRecord](schema)
  private val dataFileWriter = new DataFileWriter[GenericRecord](datumWriter)
  private val serializer = new RowSerializer(schema)
  private val _records = new AtomicInteger(0)

  dataFileWriter.create(schema, out)

  def write(row: Row): Unit = {
    val record = serializer.serialize(row)
    dataFileWriter.append(record)
    _records.incrementAndGet()
  }

  def records: Int = _records.get()

  def close(): Unit = {
    dataFileWriter.flush()
    dataFileWriter.close()
  }
} 
开发者ID:51zero,项目名称:eel-sdk,代码行数:35,代码来源:AvroWriter.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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