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


Scala FileOutputStream类代码示例

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


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


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