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

Scala FileInputStream类代码示例

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

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



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

示例1: HelloWorldSpring

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

import java.io.FileInputStream
import java.util.Properties

import org.springframework.beans.factory.BeanFactory
import org.springframework.beans.factory.support.{DefaultListableBeanFactory, PropertiesBeanDefinitionReader}

object HelloWorldSpring extends App {
  @throws(classOf[Exception])
  val factory: BeanFactory = getBeanFactory
  val mr: MessageRenderer = factory.getBean("renderer").asInstanceOf[MessageRenderer]
  val mp: MessageProvider = factory.getBean("provider").asInstanceOf[MessageProvider]
  mr.setMessageProvider(mp)
  mr.render

  @throws(classOf[Exception])
  private def getBeanFactory: BeanFactory = {
    val factory: DefaultListableBeanFactory = new DefaultListableBeanFactory
    val rdr: PropertiesBeanDefinitionReader = new PropertiesBeanDefinitionReader(factory)
    val props: Properties = new Properties
    props.load(new FileInputStream("springdi_scala/src/helloworld/beans.properties"))
    rdr.registerBeanDefinitions(props)
    return factory
  }
} 
开发者ID:BBK-PiJ-2015-67,项目名称:sdp-portfolio,代码行数:27,代码来源:HelloWorldSpring.scala


示例2: LRPmmlEvaluator

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

import java.io.{File, FileInputStream}
import java.util
import javax.xml.transform.stream.StreamSource

import org.dmg.pmml.{FieldName, Model, PMML}
import org.jpmml.evaluator.{EvaluatorUtil, FieldValue, ModelEvaluator, ModelEvaluatorFactory}
import org.jpmml.model.JAXBUtil

import scala.collection.Map
import scala.util.Try



class LRPmmlEvaluator(modelLocation: String, threshold: Option[Double]) {

  val inputStream = new FileInputStream(new File(modelLocation, "/model/PMML/PMML.xml"))
  val pmmModel: PMML = JAXBUtil.unmarshalPMML(new StreamSource(inputStream))

  val evaluatorFactory: ModelEvaluatorFactory = ModelEvaluatorFactory.newInstance()
  val evaluator: ModelEvaluator[_ <: Model] = evaluatorFactory.newModelManager(pmmModel)
  val activeFields: util.List[FieldName] = evaluator.getActiveFields
  val targetFields: util.List[FieldName] = EvaluatorUtil.getTargetFields(evaluator)
  val outputFields: util.List[FieldName] = EvaluatorUtil.getOutputFields(evaluator)

  def arguments(eval: FieldName => (FieldName, FieldValue)) = (activeFields map eval).toMap

  def getResults(result: java.util.Map[FieldName, _]) = {
    val targets = targetFields map (f => EvaluatorUtil.decode(result.get(f)))
    val outputs = outputFields map (f => result.get(f))
    Tuple3(targets.head.asInstanceOf[Double], outputs.head.asInstanceOf[Double], outputs(1).asInstanceOf[Double])
  }

  def callEvaluator(params : Map[FieldName, _]) = getResults(evaluator.evaluate(params))

  def predict(features: Features) = Try {
    val r = callEvaluator(arguments((f: FieldName) => {
      val value = features.vector(f.getValue)
      val activeValue = evaluator.prepare(f, value)
      (f, activeValue)
    }))
    new Prediction("", if (r._1 == 0.0) true else false, if (r._1 == 0) r._2 else r._3)
  }
} 
开发者ID:inneractive-opensrc,项目名称:cerberus,代码行数:46,代码来源:Evaluators.scala


示例3: XML

//设置package包名称以及导入依赖的类
package org.cg.scala.dhc.util

import java.io.{ByteArrayOutputStream, File, FileInputStream}

import scala.util.matching.Regex
import scala.xml.Elem
import scala.xml.factory.XMLLoader
import javax.xml.parsers.SAXParser

object XML extends XMLLoader[Elem] {
  override def parser: SAXParser = {
    val f = javax.xml.parsers.SAXParserFactory.newInstance()
    f.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
    f.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    f.newSAXParser()
  }
}

object FileUtil {

  def recursiveListFileInfos(baseDir: String, regex: String): Array[FileInfo] =
    recursiveListFiles(baseDir, regex).map(f => new FileInfo(f.getName, f.getCanonicalPath, f.lastModified()))

  def recursiveListFiles(baseDir: String, regex: String): Array[File] = recursiveListFiles(new File(baseDir), new Regex(regex))

  def recursiveListFiles(f: File, r: Regex): Array[File] = {
    val these = f.listFiles
    if (these != null) {
      val good = these.filter(f => r.findFirstIn(f.getName).isDefined)
      good ++ these.filter(_.isDirectory).flatMap(recursiveListFiles(_, r))
    }
    else
      new Array[File](0)
  }

  def fileToString(file: File) = {
    val inStream = new FileInputStream(file)
    val outStream = new ByteArrayOutputStream
    try {
      var reading = true
      while (reading) {
        inStream.read() match {
          case -1 => reading = false
          case c => outStream.write(c)
        }
      }
      outStream.flush()
    }
    finally {
      inStream.close()
    }
    new String(outStream.toByteArray())
  }

} 
开发者ID:curiosag,项目名称:datahubchecker,代码行数:56,代码来源:FileUtil.scala


示例4: FrameUtils

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

import java.io.{DataInputStream, File, FileInputStream}

import com.softwaremill.modemconnector.agwpe.AGWPEFrame
import com.softwaremill.modemconnector.ax25.AX25Frame

object FrameUtils {

  def ax25frameFromFile(filePath: String): AX25Frame = {
    val file: File = new File(this.getClass.getResource(filePath).getPath)
    AX25Frame(AGWPEFrame(new DataInputStream(new FileInputStream(file))).data.get)
  }

  def dataStream(filePath: String): DataInputStream = {
    val file: File = new File(this.getClass.getResource(filePath).getPath)
    new DataInputStream(new FileInputStream(file))
  }
} 
开发者ID:softwaremill,项目名称:modem-connector,代码行数:20,代码来源:FrameUtils.scala


示例5: PullRequestSampleClient

//设置package包名称以及导入依赖的类
package de.stema.pullrequests.client

import java.io.{File, FileInputStream}
import javax.inject.Inject

import de.stema.pullrequests.dto.{ProjectDTO, PullRequestDTO}
import de.stema.util.JsonObjectMapper
import play.api.libs.json.Json

import scala.concurrent.Future


class PullRequestSampleClient @Inject()(jsonObjectMapper: JsonObjectMapper
                                       ) extends PullRequestClient {

  def getPullRequests(configuration: String): Seq[Future[ProjectDTO]] = {
    val jsonFile = new File("conf/testcontent.json")

    val stream = new FileInputStream(jsonFile)
    val json = try {
      Json.parse(stream)
    } finally {
      stream.close()
    }
    val prs = jsonObjectMapper.getInstances[PullRequestDTO](json.toString())
    Seq(Future.successful(ProjectDTO("testProject", prs)))
  }
} 
开发者ID:callidustaurus,项目名称:github-api,代码行数:29,代码来源:PullRequestSampleClient.scala


示例6: fillFromEnv

//设置package包名称以及导入依赖的类
package hu.blackbelt.cd.bintray.deploy

import java.io.{File, FileInputStream}
import java.util.Properties

import org.scalatest.{BeforeAndAfter, Suite}

trait Creds extends BeforeAndAfter {
  this: Suite =>

  def fillFromEnv(prop: Properties) = {
    def put(key: String) = sys.env.get(key.replace('.','_')).map(prop.put(key.replace('_','.'), _))
    put(Access.aws_accessKeyId)
    put(Access.aws_secretKey)
    put(Access.bintray_organization)
    put(Access.bintray_user)
    put(Access.bintray_apikey)
  }

  before {
    import scala.collection.JavaConverters._
    val prop = new Properties()
    val propsFile = new File("env.properties")
    if (propsFile.exists()) {
      prop.load(new FileInputStream(propsFile))
    } else {
      fillFromEnv(prop)
    }
    prop.entrySet().asScala.foreach {
      (entry) => {
        sys.props += ((entry.getKey.asInstanceOf[String], entry.getValue.asInstanceOf[String]))
      }
    }
  }


} 
开发者ID:tsechov,项目名称:s3-bintray-deploy,代码行数:38,代码来源:Creds.scala


示例7: loadFromFile

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

import java.io.{BufferedInputStream, FileInputStream}

import org.edoardo.segmentation.SegmentationResult


	def loadFromFile(fileName: String, ipf: VolumeIPF): SegmentationResult = {
		implicit val in = new BufferedInputStream(new FileInputStream(fileName))
		checkLineIs("MFS Text 0")
		checkLineIs("{")
		checkLineIs("Level Set 0")
		checkLineIs("{")
		
		var done = false
		var regions: List[(Int, Int)] = List()
		while (!done) {
			val line: String = readLine
			if (line == "}")
				done = true
			else {
				val splitLine: Array[String] = line.split(",")
				regions ::= (splitLine(0).drop(1).toInt, splitLine(1).dropRight(1).toInt)
			}
		}
		
		checkLineIs("}")
		
		val result: Array[Array[Array[Boolean]]] = Array.fill[Boolean](ipf.width, ipf.height, ipf.depth)(false)
		for ((x, y, z) <- regions.flatMap(region => ipf.getRegionPixels(region._1, region._2)))
			result(x)(y)(z) = true
		new SegmentationResult(result)
	}
} 
开发者ID:EdoDodo,项目名称:rl-segmentation,代码行数:35,代码来源:MFS.scala


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


示例9: PelagiosRDFCrosswalk

//设置package包名称以及导入依赖的类
package models.place.crosswalks

import java.io.InputStream
import models.place._
import org.joda.time.{ DateTime, DateTimeZone }
import org.pelagios.Scalagios
import org.pelagios.api.PeriodOfTime
import java.io.File
import java.io.FileInputStream

object PelagiosRDFCrosswalk {
  
  private def convertPeriodOfTime(period: PeriodOfTime): TemporalBounds = {
    val startDate = period.start
    val endDate = period.end.getOrElse(startDate)
    
    TemporalBounds(
      new DateTime(startDate).withZone(DateTimeZone.UTC), 
      new DateTime(endDate).withZone(DateTimeZone.UTC))          
  }
  
  def fromRDF(filename: String): InputStream => Seq[GazetteerRecord] = {
    
    val sourceGazetteer = Gazetteer(filename.substring(0, filename.indexOf('.')))
  
    def convertPlace(place: org.pelagios.api.gazetteer.Place): GazetteerRecord =
      GazetteerRecord(
        GazetteerRecord.normalizeURI(place.uri),
        sourceGazetteer,
        DateTime.now().withZone(DateTimeZone.UTC),
        None,
        place.label,
        place.descriptions.map(l => Description(l.chars, l.lang)),
        place.names.map(l => Name(l.chars, l.lang)),
        place.location.map(_.geometry),
        place.location.map(_.pointLocation),
        place.temporalCoverage.map(convertPeriodOfTime(_)),
        place.category.map(category => Seq(category.toString)).getOrElse(Seq.empty[String]),
        None, // country code
        None, // population
        place.closeMatches.map(GazetteerRecord.normalizeURI(_)),
        place.exactMatches.map(GazetteerRecord.normalizeURI(_)))
    
    // Return crosswalk function
    { stream: InputStream =>
      Scalagios.readPlaces(stream, filename).map(convertPlace).toSeq }
  }
  
  def readFile(file: File): Seq[GazetteerRecord] =
    fromRDF(file.getName)(new FileInputStream(file))
  
} 
开发者ID:pelagios,项目名称:recogito2,代码行数:53,代码来源:PelagiosRDFCrosswalk.scala


示例10: DumpImporter

//设置package包名称以及导入依赖的类
package controllers.admin.gazetteers

import java.io.{ InputStream, File, FileInputStream }
import java.util.zip.GZIPInputStream
import models.place.{ GazetteerRecord, PlaceService }
import play.api.Logger
import scala.concurrent.{ Await, ExecutionContext }
import scala.concurrent.duration._

class DumpImporter {
  
  private def getStream(file: File, filename: String) =
    if (filename.endsWith(".gz"))
      new GZIPInputStream(new FileInputStream(file))
    else
      new FileInputStream(file)
  
  def importDump(file: File, filename: String, crosswalk: InputStream => Seq[GazetteerRecord])(implicit places: PlaceService, ctx: ExecutionContext) = {
    val records = crosswalk(getStream(file, filename))
    Logger.info("Importing " + records.size + " records")
    Await.result(places.importRecords(records), 60.minute)   
  }
  
} 
开发者ID:pelagios,项目名称:recogito2,代码行数:25,代码来源:DumpImporter.scala


示例11: DDApp

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

import com.virdis.{ProcessTokens, resourceManager}
import opennlp.tools.sentdetect.{SentenceDetectorME, SentenceModel}
import opennlp.tools.tokenize.{TokenizerME, TokenizerModel, WhitespaceTokenizer}


object DDApp extends ProcessTokens {


  def main(args: Array[String]): Unit = {

    println("")
    println("")
    println("Application ready .....".toUpperCase())
    println("Type in your text.")
    println("Once you are done inputting your text, go to a new line (ENTER) and then type :q or :quit to begin processing.")
    println("")
    println("")
    resourceManager.using(new BufferedReader(new InputStreamReader(System.in))) {
      stdInReader =>
        var running = true
        val buffer = new StringBuilder()
        val whiteSpaceTokenizer = WhitespaceTokenizer.INSTANCE

        resourceManager.using(new FileInputStream("lib/en-sent.bin")) {
          trainedSM =>
            val sentenceDetect = new SentenceDetectorME(new SentenceModel(trainedSM))

              while (running) {
                val line = stdInReader.readLine()
                if (line.equals(":quit") || line.equals(":q")) {
                  running = false
                  val resMap = processTokens(buffer, sentenceDetect, whiteSpaceTokenizer)

                  prettyPrinting(resMap)

                } else {
                  buffer.append(line.toLowerCase())
                  buffer.append("\n")
                }
              }
        }

    }

    System.exit(0)
  }
} 
开发者ID:virdis,项目名称:ddl-concordance,代码行数:50,代码来源:DDApp.scala


示例12: SystemUtil

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

import java.io.File
import java.io.FileInputStream
import java.security.DigestInputStream
import java.security.MessageDigest
import javax.xml.bind.DatatypeConverter

object SystemUtil {
  private val BUF_SIZE: Int = 0x1000

  def md5(file: File): Array[Byte] = {
    val md = MessageDigest.getInstance("MD5")
    val is = new FileInputStream(file)
    try {
      val dis = new DigestInputStream(is, md)
      try {
        val buf: Array[Byte] = new Array[Byte](BUF_SIZE)
        while (dis.read(buf) != -1) {}
      } finally {
        dis.close()
      }
    } finally {
      is.close()
    }
    md.digest()
  }

  def base64Md5(file: File): String = DatatypeConverter.printBase64Binary(md5(file))
} 
开发者ID:dborisenko,项目名称:data-train,代码行数:31,代码来源:SystemUtil.scala


示例13: Files

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

import java.io.FileInputStream
import java.util.UUID

import play.api.Play
import play.api.mvc.{Action, Controller, ResponseHeader, Result}
import com.google.common.io.BaseEncoding
import exceptions.GoogleAuthTokenExpired
import models.File
import play.api.libs.iteratee.Enumerator


object Files extends Controller {

  lazy val oauth2 = new utils.OAuth2(Play.current)

  def fileUpload = Action(parse.multipartFormData) { request =>
    request.body.file("file").map { picture =>
      val fileName = picture.filename
      val contentType = picture.contentType.getOrElse("text/html")
      val fstream = new FileInputStream(picture.ref.file)
      val ftext = BaseEncoding.base64.encode(Stream.continually(fstream.read).takeWhile(_ != -1).map(_.toByte).toArray)
      try {
        val user = oauth2.getUser(request.session)
        // Persist
        File.create(new File(0, user.id, fileName, contentType, ftext))
        // TODO(delyan): this should return file ID perhaps?
        Ok(fileName)
      } catch {
        case expired: GoogleAuthTokenExpired =>
          val state = UUID.randomUUID().toString
          Ok(views.html.index(None, Some(oauth2.getLoginURL(state)), List()))
            .withSession("oauth-state" -> state)
      }
    }.getOrElse {
      Redirect(routes.Users.index)
        .flashing("error" -> "Missing file")
    }
  }

  def file = Action {
    // TODO(delyan): File.get...
    Ok("{}").as("application/json")
  }

  def downloadFile(fileName: String) = Action { request =>
    val user = oauth2.getUser(request.session)
    val file = File.getByName(user.id, fileName)
    // TODO(delyan): File.get...
    val fileContent: Enumerator[Array[Byte]] = Enumerator(BaseEncoding.base64.decode(file.file))
    Result(
      header = ResponseHeader(200),
      body = fileContent
    ).as(file.content_type)
  }

} 
开发者ID:delqn,项目名称:botslandia,代码行数:59,代码来源:Files.scala


示例14: AmandroidSettings

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

import java.io.{File, FileInputStream, InputStream}

import org.ini4j.Wini
import org.argus.jawa.core.util.FileUtil


class AmandroidSettings(amandroid_home: String, iniPathOpt: Option[String]) {
  private val amandroid_home_uri = FileUtil.toUri(amandroid_home)
  private def defaultLibFiles =
    amandroid_home + "/androidSdk/android-25/android.jar" + java.io.File.pathSeparator +
    amandroid_home + "/androidSdk/support/v4/android-support-v4.jar" + java.io.File.pathSeparator +
    amandroid_home + "/androidSdk/support/v13/android-support-v13.jar" + java.io.File.pathSeparator +
    amandroid_home + "/androidSdk/support/v7/android-support-v7-appcompat.jar"
  private def defaultThirdPartyLibFile = amandroid_home + "/liblist.txt"
  private val iniUri = {
    iniPathOpt match {
      case Some(path) => FileUtil.toUri(path)
      case None => FileUtil.appendFileName(amandroid_home_uri, "config.ini")
    }
  }
  private val ini = new Wini(FileUtil.toFile(iniUri))
  def timeout: Int = Option(ini.get("analysis", "timeout", classOf[Int])).getOrElse(5)
  def dependence_dir: Option[String] = Option(ini.get("general", "dependence_dir", classOf[String]))
  def debug: Boolean = ini.get("general", "debug", classOf[Boolean])
  def lib_files: String = Option(ini.get("general", "lib_files", classOf[String])).getOrElse(defaultLibFiles)
  def third_party_lib_file: String = Option(ini.get("general", "third_party_lib_file", classOf[String])).getOrElse(defaultThirdPartyLibFile)
  def actor_conf_file: InputStream = Option(ini.get("concurrent", "actor_conf_file", classOf[String])) match {
    case Some(path) => new FileInputStream(path)
    case None => getClass.getResourceAsStream("/application.conf")
  }
  def static_init: Boolean = ini.get("analysis", "static_init", classOf[Boolean])
  def parallel: Boolean = ini.get("analysis", "parallel", classOf[Boolean])
  def k_context: Int = ini.get("analysis", "k_context", classOf[Int])
  def sas_file: String = Option(ini.get("analysis", "sas_file", classOf[String])).getOrElse(amandroid_home + File.separator + "taintAnalysis" + File.separator + "sourceAndSinks" + File.separator + "TaintSourcesAndSinks.txt")
  def injection_sas_file: String = Option(ini.get("analysis", "injection_sas_file", classOf[String])).getOrElse(amandroid_home + File.separator + "taintAnalysis" + File.separator + "sourceAndSinks" + File.separator + "IntentInjectionSourcesAndSinks.txt")
} 
开发者ID:arguslab,项目名称:Argus-SAF,代码行数:39,代码来源:AmandroidSettings.scala


示例15: handleAndroidXMLFiles

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

import java.io.File
import java.util.zip.ZipEntry
import java.util.zip.ZipInputStream
import java.io.FileInputStream


	def handleAndroidXMLFiles(apk: File, fileNameFilter: Set[String],
			handler: AndroidXMLHandler) = {

		try {
			var archive: ZipInputStream = null
			try {
				archive = new ZipInputStream(new FileInputStream(apk))
				var entry: ZipEntry = null
				entry = archive.getNextEntry()
				while (entry != null) {
					val entryName = entry.getName()
					handler.handleXMLFile(entryName, fileNameFilter, archive)
					entry = archive.getNextEntry()
				}
			}
			finally {
				if (archive != null)
					archive.close()
			}
		}
		catch {
		  case e: Exception =>
				e.printStackTrace()
				if (e.isInstanceOf[RuntimeException])
					throw e.asInstanceOf[RuntimeException]
				else
					throw new RuntimeException(e)
		}
	}
} 
开发者ID:arguslab,项目名称:Argus-SAF,代码行数:39,代码来源:AndroidXMLParser.scala


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


示例17: read

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

import java.io.{BufferedInputStream, FileInputStream, InputStream}

trait BufferedInput {
  this: InputStream =>

  val size: Int = 100
  val buffer = new BufferedInputStream(this, size)
  override def read(): Int = buffer.read
}

object Test08 extends App {
  val txtFile = getClass.getResource("/sample.txt")
  val file = new FileInputStream(new java.io.File(txtFile.getPath)) with BufferedInput

  var byte = file.read()
  while (byte != -1){
    print(byte.toChar)
    byte = file.read()
  }

  // print(Iterator.continually(file.read).takeWhile(_ != -1).map(_.toChar).mkString)
} 
开发者ID:johnnyqian,项目名称:scala-for-the-impatient,代码行数:25,代码来源:08.scala


示例18: Img2TxtProcessor

//设置package包名称以及导入依赖的类
package pl.mojepanstwo.sap.toakoma.processors

import java.io.{File, FileInputStream, InputStreamReader}

import org.springframework.batch.item.ItemProcessor
import pl.mojepanstwo.sap.toakoma._

import scala.xml.{Elem, Node, XML}

import scala.xml.transform.RewriteRule
import sys.process._


class Img2TxtProcessor extends ItemProcessor[Model, Model] {

  override def process(item:Model): Model = {

    item.linksHtml.foreach { case (key, dirPath) =>
      try {
        val xml = XML.load(new InputStreamReader(new FileInputStream(item.xmlPath(key)), "UTF-8"))

        val changed = new RewriteRule {
          override def transform(n: Node): Seq[Node] = n match {
            case elem @ Elem(_, "img", _, _, child @ _*) => {
              val src = elem.attribute("src").get
              val imageFile = new File(dirPath + "/" + src)

              val cmd = "tesseract " +
                imageFile.getAbsolutePath + " " +
                "stdout " +
                "-l pol"
              var result = cmd !!

              if(Option(result).exists(_.trim.isEmpty)) return n

              result = result.replaceAll("-\n", "")
              result = result.replaceAll("—\n", "")

              return(<textFromImg>{result}</textFromImg>)
            }
            case elem: Elem => elem copy (child = elem.child flatMap (this transform))
            case other => other
          }
        } transform xml

        XML.save(dirPath + "/text_from_image.xml", changed(0), "UTF-8", true)
        item.xmlPath(key) = dirPath + "/text_from_image.xml"
      } catch {
        case e: Throwable => println(e.printStackTrace())
      }
    }

    item
  }
} 
开发者ID:PrawoPolskie,项目名称:toakoma,代码行数:56,代码来源:Img2TxtProcessor.scala


示例19: ReadRectangles

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

import java.io.IOException
import java.io.DataInputStream
import java.io.FileInputStream
import core.scala.RectangleTuple

object ReadRectangles {
  
  def readDoublePointRecs(dimension : Int, dis : DataInputStream) : Stream[RectangleTuple] = {
      val leftP =  new  Array[Double](dimension)
      val rightP = new Array[Double](dimension)
      for (i <- 0 until dimension){
        leftP(i) = dis.readDouble()
      }
      for (i <- 0 until dimension){
        rightP(i) = dis.readDouble()
      }
      new RectangleTuple(leftP, rightP) #:: readDoublePointRecs(dimension, dis)
  }

  
  def main(args: Array[String]){
    
    val dis = new DataInputStream(new FileInputStream("/home/da/data/rea02.rec"))
    try{
      readDoublePointRecs(2, dis).take(10).foreach { x => println(x) }
    }catch {
      case e : IOException => e.printStackTrace();
    }finally {
      dis.close()
    }
  }
  
} 
开发者ID:daniarleagk,项目名称:rbulkloading,代码行数:36,代码来源:ReadRectangles.scala


示例20: Of

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

import java.io.{FileInputStream, File}
import java.util.logging.LogManager

import grizzled.slf4j.Logger

trait LoggingConfiguration {
  val logConfigFile = "logging.properties"
  val current = new File(".", logConfigFile)
  val logConfigStream = if (current.exists()) new FileInputStream(current) else classOf[LoggingConfiguration].getResourceAsStream("/" + logConfigFile)
  val logManager: LogManager = LogManager.getLogManager
  logManager.readConfiguration(logConfigStream)

  def getLogger(category: Class[_]): Logger = {
    Logger(category)
  }
} 
开发者ID:jeroenvanmaanen,项目名称:crystallize,代码行数:19,代码来源:LoggingConfiguration.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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