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

Scala FileOutputStream类代码示例

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

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



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

示例1: Frontend

//设置package包名称以及导入依赖的类
package compiler
import java.io.{BufferedOutputStream, FileOutputStream}

object Frontend extends App {
  if (args.length != 2) {
    println(
      """
        |Wrong number of arguments:
        |Arguments should be <sourceFile.pas> <outputClassName>
      """.stripMargin)
    System.exit(1)
  }
  val filePath = args(0)
  val className = args(1)

  Compiler.compileFile(filePath, className) match {
    case Left(errors) => println("Compilation errors:"); errors.foreach(println)
    case Right(bytes) =>
      val outputStream = new BufferedOutputStream(new FileOutputStream(s"$className.class"))
      Stream.continually(outputStream.write(bytes))
      outputStream.close()
  }
} 
开发者ID:darthorimar,项目名称:pascalJvm,代码行数:24,代码来源:Frontend.scala


示例2: CodeGeneratorTest

//设置package包名称以及导入依赖的类
import java.io.{BufferedOutputStream, FileOutputStream}

import compiler.codeGenerator.CodeGenerator
import compiler.lexer.Lexer
import compiler.parser.Parser
import org.scalatest._


class CodeGeneratorTest extends FlatSpec with Matchers {

  private def tokenizeAndParse(code: String) = {
    val tokens = Lexer(code).right.get
    Parser(tokens)
  }

  "Code generator" should "work fine" in {
    val code =
      """
        |program;
        |  var i,b: Integer;
        |begin
        | for i := 100 downto 1 do
        |  begin
        |    b :=i + 10;
        |  end;
        |end.""".stripMargin

    tokenizeAndParse(code) match {
      case Left(errors) => println(errors)
      case Right(bytes) =>
        val ast = tokenizeAndParse(code).right.get
        val bytes = CodeGenerator(ast, "Main")

        val bos = new BufferedOutputStream(new FileOutputStream("Main.class"))
        Stream.continually(bos.write(bytes))
        bos.close()
    }

  }


} 
开发者ID:darthorimar,项目名称:pascalJvm,代码行数:43,代码来源:CodeGeneratorTest.scala


示例3: ArnoldC

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

import java.io.FileOutputStream
import org.arnoldc.ast.RootNode

object ArnoldC {
  def main(args: Array[String]) {
    if (args.length < 1) {
      println("Usage: ArnoldC [-run|-declaim] [FileToSourceCode]")
      return
    }
    val filename = getFilNameFromArgs(args)
    val sourceCode = scala.io.Source.fromFile(filename).mkString
    val a = new ArnoldGenerator()
    val classFilename = if (filename.contains('.')) {
      filename.replaceAll("\\.[^.]*$", "")
    }
    else {
      filename
    }
    val (bytecode, root) = a.generate(sourceCode, classFilename)

    val out = new FileOutputStream(classFilename + ".class")
    out.write(bytecode)
    out.close()

    processOption(getCommandFromArgs(args), classFilename, root)

  }
  
  def getFilNameFromArgs(args:Array[String]):String = args.length match {
    case 1 => args(0)
    case 2 => args(1)
    case _ => throw new RuntimeException("WHAT THE FUCK DID I DO WRONG!")
  }

  def getCommandFromArgs(args:Array[String]):String = args.length match {
    case 2 => args(0)
    case 1 => ""
    case _ => throw new RuntimeException("WHAT THE FUCK DID I DO WRONG!")
  }

  def processOption(command:String, argFunc: => String, root: RootNode):Unit = command match {
    case "-run" => Executor.execute(argFunc)
    case "-declaim" => Declaimer.declaim(root, argFunc)
    case _ =>
  }

} 
开发者ID:derlorenz,项目名称:VongSprech,代码行数:50,代码来源:ArnoldC.scala


示例4: store

//设置package包名称以及导入依赖的类
package ru.fediq.scrapingkit.backend

import java.io.{BufferedOutputStream, FileOutputStream, PrintWriter}

import ru.fediq.scrapingkit.scraper.ScrapedEntity
import ru.fediq.scrapingkit.util.Utilities

import scala.concurrent.Future

trait FeedExporter extends AutoCloseable {
  def store[T <: ScrapedEntity](entity: T): Future[_]

  override def close() = {
    // Do nothing
  }
}

class NoOpFeedExporter extends FeedExporter {
  override def store[T <: ScrapedEntity](entity: T) = {
    Future.successful()
  }
}

class JsonLinesFeedExporter(
  path: String
) extends FeedExporter {
  val writer = new PrintWriter(new BufferedOutputStream(new FileOutputStream(path, true)))

  implicit val dispatcher = Utilities.singleDaemonDispatcher("feed-exporter")

  override def store[T <: ScrapedEntity](entity: T) = Future {
    writer.println(entity.dump)
  }

  override def close() = {
    writer.close()
  }
} 
开发者ID:fediq,项目名称:scraping-kit,代码行数:39,代码来源:FeedExporter.scala


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


示例6: MALImage

//设置package包名称以及导入依赖的类
package me.abarrow.ScalaSubNet.mal

import java.io.File
import java.io.FileOutputStream
import java.net.URL
import org.jsoup.Jsoup
import org.jsoup.parser.Parser
import java.nio.channels.Channels

object MALImage {
  def saveMainImage(animeID:Int, imagePath:File):Boolean = {
    val doc = Jsoup.parse(new URL(MALURLs.MAL_ANIME_PAGE_PREFIX + animeID.toString()), 60000)
    val mainImage = doc.select("img.ac").first()
    if (mainImage == null) {
      return false
    }
    val imgSrc = mainImage.attr("src")
    val rbc = Channels.newChannel(new URL(imgSrc).openStream())
    val fos = new FileOutputStream(imagePath)
    try {
      fos.getChannel().transferFrom(rbc, 0, Long.MaxValue)
    } finally {
      fos.close()
      rbc.close()
    }
    true
  }
} 
开发者ID:Abarrowman,项目名称:ScalaSubNet,代码行数:29,代码来源:MALImage.scala


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


示例8: Test10

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

import java.io.{FileInputStream, FileOutputStream, ObjectInputStream, ObjectOutputStream}
import scala.collection.mutable.ArrayBuffer

object Test10 extends App {

  case class Person(val name: String) extends Serializable {
    val friends = new ArrayBuffer[Person]

    def addFriend(p: Person) {
      friends += p
    }

    def isFriendOf(p: Person): Boolean = {
      friends.contains(p)
    }
  }

  val tom = Person("tom")
  val jerry = Person("jerry")
  val johnny = Person("johnny")

  tom.addFriend(johnny)
  jerry.addFriend(johnny)

  val persons = Array(tom, jerry, johnny)

  val out = new ObjectOutputStream(new FileOutputStream("src/Chapter09/10.obj"))
  out.writeObject(persons)
  out.close()

  val in = new ObjectInputStream(new FileInputStream("src/Chapter09/10.obj"))
  val Array(_tom,_jerry,_johnny) = in.readObject().asInstanceOf[Array[Person]]

  assert(_tom isFriendOf _johnny)
  assert(_jerry isFriendOf _johnny)
  // assert(_tom isFriendOf _jerry)
} 
开发者ID:johnnyqian,项目名称:scala-for-the-impatient,代码行数:40,代码来源:10.scala


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


示例10: FuntikC

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

import java.io.FileOutputStream
import org.funtikc.ast.RootNode

object FuntikC {
  def main(args: Array[String]) {
    if (args.length < 1) {
      println("Usage: FuntikC [-run|-declaim] [FileToSourceCode]")
      return
    }
    val filename = getFilNameFromArgs(args)
    val sourceCode = scala.io.Source.fromFile(filename).mkString
    val a = new FuntikGenerator()
    val classFilename = if (filename.contains('.')) {
      filename.replaceAll("\\.[^.]*$", "")
    }
    else {
      filename
    }
    val (bytecode, root) = a.generate(sourceCode, classFilename)

    val out = new FileOutputStream(classFilename + ".class")
    out.write(bytecode)
    out.close()

    processOption(getCommandFromArgs(args), classFilename, root)

  }
  
  def getFilNameFromArgs(args:Array[String]):String = args.length match {
    case 1 => args(0)
    case 2 => args(1)
    case _ => throw new RuntimeException("? ???? ? ????????, ?? ?????????? ?? ??????")
  }

  def getCommandFromArgs(args:Array[String]):String = args.length match {
    case 2 => args(0)
    case 1 => ""
    case _ => throw new RuntimeException("? ???? ? ????????, ?? ?????????? ?? ??????")
  }

  def processOption(command:String, argFunc: => String, root: RootNode):Unit = command match {
    case "-run" => Executor.execute(argFunc)
    case "-declaim" => Declaimer.declaim(root, argFunc)
    case _ =>
  }

} 
开发者ID:iogr,项目名称:FuntikC,代码行数:50,代码来源:FuntikC.scala


示例11: expectationsFolder

//设置package包名称以及导入依赖的类
package de.zalando.swagger

import java.io.{ File, FileOutputStream }

import scala.io.Source


trait ExpectedResults {

  val resourcesPath = "swagger-parser/src/test/resources/"

  def expectationsFolder: String = "/expected_results/"

  def dump(result: String, file: File, suffix: String): Unit = {
    if (result.nonEmpty) {
      val newFile = target(file, suffix)
      newFile.getParentFile.mkdirs()
      newFile.delete()
      newFile.createNewFile()
      val out = new FileOutputStream(newFile)
      out.write(result.getBytes)
      out.close()
    }
  }

  def asInFile(file: File, suffix: String): String = {
    val expectedFile = target(file, suffix)
    if (expectedFile.canRead) {
      val src = Source.fromFile(expectedFile)
      val result = src.getLines().mkString("\n")
      src.close()
      result
    } else
      ""
  }

  def target(file: File, suffix: String): File =
    new File(file.getParentFile.getParent + expectationsFolder + file.getName + "." + suffix)

  def clean(str: String): String = str.split("\n").map(_.trim).mkString("\n")
} 
开发者ID:LappleApple,项目名称:api-first-hand,代码行数:42,代码来源:ExpectedResults.scala


示例12: MerkelOnRails

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

import java.io.FileOutputStream

import merkelonrails.ast.RootNode

object MerkelOnRails {
  def main(args: Array[String]) {
    if (args.length < 1) {
      println("Usage: ArnoldC [-run|-declaim] [FileToSourceCode]")
      return
    }
    val filename = getFilNameFromArgs(args)
    val sourceCode = scala.io.Source.fromFile(filename).mkString
    val a = new MerkelGenerator()
    val classFilename = if (filename.contains('.')) {
      filename.replaceAll("\\.[^.]*$", "")
    }
    else {
      filename
    }
    val (bytecode, root) = a.generate(sourceCode, classFilename)

    val out = new FileOutputStream(classFilename + ".class")
    out.write(bytecode)
    out.close()

    processOption(getCommandFromArgs(args), classFilename, root)

  }

  def getFilNameFromArgs(args:Array[String]):String = args.length match {
    case 1 => args(0)
    case 2 => args(1)
    case _ => throw new RuntimeException("WHAT THE FUCK DID I DO WRONG!")
  }

  def getCommandFromArgs(args:Array[String]):String = args.length match {
    case 2 => args(0)
    case 1 => ""
    case _ => throw new RuntimeException("WHAT THE FUCK DID I DO WRONG!")
  }

  def processOption(command:String, argFunc: => String, root: RootNode):Unit = command match {
    case "-run" => Executor.execute(argFunc)
    case _ =>
  }

} 
开发者ID:lehoffma,项目名称:MerkelOnRails,代码行数:50,代码来源:MerkelOnRails.scala


示例13: StringInterpolation

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

import StringContext.treatEscapes
import java.io.{FileOutputStream, File, PrintWriter}

object StringInterpolation {

  implicit class WriteScore(val sc: StringContext) extends AnyVal {

    def write(args: Any*): String = {

      checkLengths(sc.parts.length, args.length)
      val strings = sc.parts.iterator
      val expressions = args.iterator
      val buf = new StringBuffer(treatEscapes(strings.next))
      while (strings.hasNext) {
        buf.append(expressions.next)
        buf.append(treatEscapes(strings.next))
      }
      val message: String = writeToFile(buf.toString)
      message
    }

    private def checkLengths(partLen: Int, argLen: Int) = {

      if (partLen != argLen + 1) {
        throw new IllegalArgumentException("wrong number of arguments")
      }
    }

    private def writeToFile(record: String): String = {

      val writeStatus: String = try {
        val writer = new PrintWriter(new FileOutputStream(new File("./src/test/scala/resources/output"),true))
        writer.println(record)
        writer.close()
        "File written successfully"
      }
      catch {
        case e: Exception => "Cannot write to the file"
      }
      writeStatus
    }
  }
} 
开发者ID:knoldus,项目名称:string-interpolation-example,代码行数:46,代码来源:StringInterpolation.scala


示例14: Pkcs12ConvertorSpec

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

import java.io.{FileOutputStream, StringReader}
import java.math.BigInteger
import java.time.{Duration, Instant}
import java.util.Date

import org.bouncycastle.asn1.oiw.OIWObjectIdentifiers
import org.bouncycastle.asn1.x500.X500NameBuilder
import org.bouncycastle.asn1.x500.style.BCStyle
import org.bouncycastle.asn1.x509.AlgorithmIdentifier
import org.bouncycastle.cert.X509v3CertificateBuilder
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter
import org.bouncycastle.crypto.util.PrivateKeyFactory
import org.bouncycastle.operator.bc.BcRSAContentSignerBuilder
import org.specs2.mutable.Specification

class Pkcs12ConvertorSpec extends Specification {

  "Pkcs12Convertor" should {

    "parsePrivateKey" in {
      val keyPair = RSAKeyPairFactory.generate
      val pem = RSAKeyPairFactory.privateKeyToString(keyPair)
      val reader = new StringReader(pem)

      val pk = Pkcs12Convertor.parsePrivateKey(reader)
      keyPair.getPrivate.getEncoded must_== pk.getEncoded
    }

    "parseCertificate" in {
      val keyPair = RSAKeyPairFactory.generate
      val builder = new X500NameBuilder()
      builder.addRDN(BCStyle.C, "JP")
      builder.addRDN(BCStyle.CN, "Pigumer Group")
      val csr = CertificationSigningRequestFactory.generate(builder.build(), keyPair)

      val now = Instant.now()
      val notBefore = new Date(now.toEpochMilli)
      val notAfter = new Date(now.plus(Duration.ofDays(365)).toEpochMilli)

      val b = new X509v3CertificateBuilder(csr.getSubject, BigInteger.valueOf(1L), notBefore, notAfter, csr.getSubject, csr.getSubjectPublicKeyInfo)

      val sigAlgId = new AlgorithmIdentifier(OIWObjectIdentifiers.sha1WithRSA)
      val digAlgId = new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1)

      val privateKeyInfo = PrivateKeyFactory.createKey(keyPair.getPrivate.getEncoded)
      val contentSigner = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyInfo)
      val certificate = new JcaX509CertificateConverter().getCertificate(b.build(contentSigner))

      val os = new FileOutputStream("test.p12")
      try {
        Pkcs12Convertor.write(os, keyPair.getPrivate, "test".toCharArray, certificate)
      } finally {
        os.close
      }

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


示例15: Serialisation

//设置package包名称以及导入依赖的类
package root.core.serialisation

import java.io.{FileInputStream, FileOutputStream, ObjectInputStream, ObjectOutputStream}

import scala.util.control.NonFatal


object Serialisation extends App {

  val fileName = "tempData.ser"

  val obj = Object
  val map = Map("key" -> obj)

  // deserialize object with not serializable filed

  serializeObject(obj)
  val desObj = deserializeObj
  assert(desObj.get eq obj, "deserialized obj should be the same")


//  serializeObject(map)
//  val desMap = deserializeObj
//  assert(desMap.get.asInstanceOf[map.type]("key") == map, "deserialized map should be the same")

  private def deserializeObj: Option[AnyRef] = {
    try {
      val fis = new FileInputStream(fileName)
      val ois = new ObjectInputStream(fis)
      Some(ois.readObject())
    } catch { case NonFatal(e) =>
        println(s"Deserialization fail $e")
        None
    }
  }

  private def serializeObject(obj: AnyRef) {
    try {
      val fos = new FileOutputStream(fileName)
      val oos = new ObjectOutputStream(fos)
      oos.writeObject(obj)
      oos.close()
    } catch { case NonFatal(e) =>
        println(s"Serialization fail $e")
    }
  }

}

object Object extends Serializable {
  @transient private val logger = new Logger()
}

class Logger {
  def log() = println("log")
} 
开发者ID:RicoGit,项目名称:scala-core,代码行数:57,代码来源:Serialisation.scala


示例16: Log4j2MergeStrategy

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

import java.io.{FileOutputStream, File}

import scala.collection.JavaConverters.asJavaEnumerationConverter

import org.apache.logging.log4j.core.config.plugins.processor.PluginCache

object Log4j2MergeStrategy {
  val plugincache: MergeStrategy = new MergeStrategy {
    val name = "log4j2::plugincache"
    def apply(tempDir: File, path: String, files: Seq[File]): Either[String, Seq[(File, String)]] = {
      val file = MergeStrategy.createMergeTarget(tempDir, path)
      val out = new FileOutputStream(file)

      val aggregator = new PluginCache()
      val filesEnum = files.toIterator.map(_.toURI.toURL).asJavaEnumeration

      try {
          aggregator.loadCacheFiles(filesEnum)
          aggregator.writeCache(out)
          Right(Seq(file -> path))
      }
      finally {
          out.close()
      }
    }
  }
} 
开发者ID:idio,项目名称:sbt-assembly-log4j2,代码行数:30,代码来源:Log4j2MergeStrategy.scala


示例17: Module01

//设置package包名称以及导入依赖的类
import java.io.{File, FileOutputStream, PrintWriter}
import java.util.Calendar

class Module01 (
                 val name: String = "Module-01"
               ) {
  def someHandyFunction(): String = "Handy function output."

  def log(msg: String): Unit = {
    val filename_out = s"var/log/${module.name}.log"
    val writer = new PrintWriter(new FileOutputStream(new File(filename_out), true))
    writer.write(s"[${Calendar.getInstance().getTime}] $msg\n")
    writer.close()
  }
}

val module = new Module01()
module.log(s"${module.name} started!")
module.log(s"${module.name} ended!")

println(s"${module.name} finished successfully!") 
开发者ID:ClydeMachine,项目名称:DynamicModuleMonitor,代码行数:22,代码来源:Module01.scala


示例18: LocalStore

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

import java.io.FileOutputStream
import java.math.BigInteger
import java.nio.file.{Files, Paths}
import javax.crypto.SecretKey

import org.ipfs.api.Base58
import org.jboss.netty.util.CharsetUtil


object LocalStore {
  def fileName(secretKey: SecretKey) = "/home/mats/tmp/" + Base58.encode(secretKey.getEncoded)    // TODO: Probably won't work on other machine :-)

  def save(user: User, password: String) = {
    val coreUserData = CoreUserData(user)
    val secretKey = Crypto.reCreateSecretKey(password)
    val json = JSON.toJsonString(coreUserData)
    val encryptedJSONBytes = Crypto.encryptWithSymmetricKey(json.getBytes(CharsetUtil.UTF_8), secretKey)
    val fos = new FileOutputStream(fileName(secretKey))
    fos.write(encryptedJSONBytes)
    fos.close()
  }

  def retrieve(password: String) = {
    val secretKey = Crypto.reCreateSecretKey(password)
    val path = Paths.get(fileName(secretKey))
    val encryptedJsonBytes = Files.readAllBytes(path)
    val jsonBytes = Crypto.decryptWithSymmetricKey(encryptedJsonBytes, secretKey)
    val json = new String(jsonBytes, CharsetUtil.UTF_8)
    val coreUserData = JSON.fromJsonString[CoreUserData](json)
    val privateKey = Crypto.getPrivateKeyFromBigIntegers(coreUserData.privateKeyBigIntegerComponentsAsStrings.toSeq.map(s => new BigInteger(s)))
    val publicKey = Crypto.getPublicKeyFromEncoded(coreUserData.encodedPublicKey)
    val recreatedUser = new User(coreUserData.name, privateKey, publicKey)
    coreUserData.bubbleHandles.foreach(bh => recreatedUser.addBubbleHandle(bh))
    coreUserData.friends.foreach(f => recreatedUser.friends.add(f))

    recreatedUser
  }
} 
开发者ID:matshenricson,项目名称:xyztr,代码行数:41,代码来源:LocalStore.scala


示例19: ZipFileIteratorSpec

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

import java.io.{File, FileInputStream, FileOutputStream}
import java.util.zip.{ZipEntry, ZipOutputStream}

import com.s3dropbox.lambda.ZipFileIterator.ZipFileEntry


class ZipFileIteratorSpec extends UnitSpec {

  describe("When given a valid zip file with more than one compressed file") {
    it("should iterate over the compressed files and provide their file name and contents") {
      val entries: Array[(String, Array[Byte])] =
        (1 to 5)
          .map((fileNum: Int) => {
            (s"file_$fileNum", s"This is the contents of file $fileNum".getBytes)
          })
          .toArray
      runZipFileTest(entries)
    }
  }

  describe("when given a zip file containing a single large 1MB file") {
    it("should decompress the single large file") {
      val entries: Array[(String, Array[Byte])] = Array(
        ("some_file", (1 to 1024 * 1024).map(_.toByte).toArray)
      )
      runZipFileTest(entries)
    }
  }

  def runZipFileTest(entries: Array[(String, Array[Byte])]): Unit = {
    var index: Int = 0
    val zipFileIter: ZipFileIterator = new ZipFileIterator(new FileInputStream(zipFile(entries)))
    zipFileIter.foreach((zipFileEntry: ZipFileEntry) => {
      assert(zipFileEntry.filename == entries(index)._1)
      assert(zipFileEntry.data sameElements entries(index)._2)
      index += 1
    })
    zipFileIter.close()
  }

  def zipFile(entries: Array[(String, Array[Byte])]): File = {
    val temp: File = File.createTempFile("temp-zip-file", ".zip")
    temp.deleteOnExit()

    val zos: ZipOutputStream = new ZipOutputStream(new FileOutputStream(temp))
    entries.foreach((entry: (String, Array[Byte])) => {
      val filename: String = entry._1
      val contents: Array[Byte] = entry._2

      val zentry: ZipEntry = new ZipEntry(filename)
      zos.putNextEntry(zentry)
      zos.write(contents)
      zos.closeEntry()
    })
    zos.close()

    temp
  }
} 
开发者ID:ErrorsAndGlitches,项目名称:S3DropboxLambda,代码行数:62,代码来源:ZipFileIteratorSpec.scala


示例20: ElmTypeMain

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

import elmtype._
import java.io.FileOutputStream
import shapeless._
import shapeless.ops.hlist.LiftAll
import shapeless.ops.hlist.ToTraversable

case class ElmTypeMain(list: List[CombinedType[_]]) {
  def main(args: Array[String]): Unit = {
    val target = args(0) match {
      case "-" => System.out
      case x => new FileOutputStream(x)
    }
    val data = list.map(AST.typeAST).map(AST.code).reduce(_ ++ _).render
    target.write(io.Codec.toUTF8(data))
    target.close
  }
}

case class ToElmTypes[L <: HList]() {
  def apply[Lift <: HList](implicit ev1: LiftAll.Aux[CombinedType, L, Lift], ev2: ToTraversable[Lift, List]): ev2.Out =
    ev2(ev1.instances)
} 
开发者ID:reactormonk,项目名称:scala-elm-types,代码行数:25,代码来源:ElmTypeMain.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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