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

Scala IOException类代码示例

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

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



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

示例1: SourceTrackingMonitorTest

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

import com.twitter.finagle.{Failure, RequestException}
import java.io.IOException
import java.util.logging.{Level, Logger}
import org.junit.runner.RunWith
import org.mockito.Matchers.{any, eq => mockitoEq}
import org.mockito.Mockito.{never, verify}
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner
import org.scalatest.mock.MockitoSugar

@RunWith(classOf[JUnitRunner])
class SourceTrackingMonitorTest extends FunSuite with MockitoSugar {
  test("handles unrolling properly") {
    val logger = mock[Logger]
    val monitor = new SourceTrackingMonitor(logger, "qux")
    val e = new Exception
    val f1 = new Failure("foo", Some(e), sources = Map(Failure.Source.Service -> "tweet"))
    val f2 = new Failure("bar", Some(f1))
    val exc = new RequestException(f2)
    exc.serviceName = "user"
    monitor.handle(exc)
    verify(logger).log(
      Level.SEVERE,
      "The 'qux' service " +
        Seq("user", "tweet").mkString(" on behalf of ") +
        " threw an exception",
      exc
    )
  }

  test("logs IOExceptions at Level.FINE") {
    val logger = mock[Logger]
    val ioEx = new IOException("hi")
    val monitor = new SourceTrackingMonitor(logger, "umm")
    monitor.handle(ioEx)
    verify(logger).log(mockitoEq(Level.FINE), any(), mockitoEq(ioEx))
  }

  test("logs Failure.rejected at Level.FINE") {
    val logger = mock[Logger]
    val monitor = new SourceTrackingMonitor(logger, "umm")
    val rejected = Failure.rejected("try again")
    monitor.handle(rejected)

    verify(logger).log(mockitoEq(Level.FINE), any(), mockitoEq(rejected))
    verify(logger, never()).log(mockitoEq(Level.WARNING), any(), mockitoEq(rejected))
  }
} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:51,代码来源:SourceTrackingMonitorTest.scala


示例2: ChannelHelper

//设置package包名称以及导入依赖的类
package us.illyohs.sinked.helper

import java.io.{File, FileWriter, IOException, Writer}
import java.util

import com.google.gson.{FieldNamingPolicy, Gson, GsonBuilder}
import org.spongepowered.api.Sponge
import us.illyohs.sinked.Sinked
import us.illyohs.sinked.channel.Channel

object ChannelHelper {

  val chanList:util.List[Channel] = new  util.ArrayList[Channel]()

  val sinked:Sinked = null
  val channelPath = "./channels/"

  val channelDir = new File(channelPath)

  def initChannel: Unit = {
    chanList.add(new GlobalChannel)
    chanList.add(new LocalChannel)
    if (!channelDir.exists()) {
      //      sinked.getLogger.warn("Channel directory not found!")
      //      sinked.getLogger.info("Now creating channel directory")

      channelDir.mkdir()
      val gson: Gson = new GsonBuilder()
        .setPrettyPrinting()
        .serializeNulls()
        .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
        .create()
      for (i <- 0 to 1) {
        val ch = chanList.get(i)
        val json = gson.toJson(ch)
        val w: Writer = new FileWriter(channelPath + ch.getName + ".json")
        try {
          w.write(json)
          w.close()
          //          sinked.getLogger.info("Created default channel: " +ch.getName)
        } catch {
          case e: IOException => e.printStackTrace()
        }
      }
      //      createDefualtjons
    }
  }


  case class GlobalChannel() extends Channel("Global", "", "G", "", "", false, true, false, false, true)
  case class LocalChannel() extends Channel("Local", "", "L", "", "", false, true, false, false, false)
} 
开发者ID:DragonTechMC,项目名称:Sinked,代码行数:53,代码来源:ChannelHelper.scala


示例3: SnapshotDirectoryFailureSpec

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

import akka.testkit.{ ImplicitSender, EventFilter, TestEvent, AkkaSpec }
import java.io.{ IOException, File }
import akka.actor.{ ActorInitializationException, Props, ActorRef }

object SnapshotDirectoryFailureSpec {
  val inUseSnapshotPath = "target/inUseSnapshotPath"

  class TestProcessor(name: String, probe: ActorRef) extends Processor {

    override def persistenceId: String = name

    override def preStart(): Unit = ()

    def receive = {
      case s: String               ? saveSnapshot(s)
      case SaveSnapshotSuccess(md) ? probe ! md.sequenceNr
      case other                   ? probe ! other
    }
  }
}

class SnapshotDirectoryFailureSpec extends AkkaSpec(PersistenceSpec.config("leveldb", "SnapshotDirectoryFailureSpec", extraConfig = Some(
  s"""
    |akka.persistence.snapshot-store.local.dir = "${SnapshotDirectoryFailureSpec.inUseSnapshotPath}"
  """.stripMargin))) with ImplicitSender {

  import SnapshotDirectoryFailureSpec._

  val file = new File(inUseSnapshotPath)

  override protected def atStartup() {
    if (!file.createNewFile()) throw new IOException(s"Failed to create test file [${file.getCanonicalFile}]")
  }

  override protected def afterTermination() {
    if (!file.delete()) throw new IOException(s"Failed to delete test file [${file.getCanonicalFile}]")
  }

  "A local snapshot store configured with an failing directory name " must {
    "throw an exception at startup" in {
      EventFilter[ActorInitializationException](occurrences = 1).intercept {
        val processor = system.actorOf(Props(classOf[TestProcessor], "SnapshotDirectoryFailureSpec-1", testActor))
        processor ! "blahonga"
      }
    }
  }
} 
开发者ID:love1314sea,项目名称:akka-2.3.16,代码行数:50,代码来源:SnapshotDirectoryFailureSpec.scala


示例4: foo

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

def foo: String = {
  	val in = new BufferedReader(new InputStreamReader(System.in))
 	try {
		print("Escribe texto: ")
		in.readLine
  	}
  	catch {
    	case e: IOException => { e.printStackTrace(); e.toString() }
  	}
  	finally {
    	in.close()
  	}
}

println("Return value: " + foo) 
开发者ID:romanarranz,项目名称:NTP,代码行数:20,代码来源:excepcionesTryCatchFinally.scala


示例5: Scraper

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

import java.io.IOException

import scala.io.Source


object Scraper {
  def getPageSize(url: String) = {
    val page = getPage(url)
    if (url == null) -1 else page.mkString.length
  }

  def getPage(url: String) = {
    try {
      Source.fromURL(url)
    } catch {
      case ioe: IOException => null
    }
  }
} 
开发者ID:nbokmans,项目名称:7l7wScala,代码行数:22,代码来源:Scraper.scala


示例6: FlowerDataSetIteratorFeaturized

//设置package包名称以及导入依赖的类
package org.dl4scala.examples.transferlearning.vgg16.dataHelpers

import java.io.File


object FlowerDataSetIteratorFeaturized {

  private val log = org.slf4j.LoggerFactory.getLogger(FlowerDataSetIteratorFeaturized.getClass)

  var featureExtractorLayer: String = FeaturizedPreSave.featurizeExtractionLayer

  def setup(featureExtractorLayerArg: String): Unit = {
    featureExtractorLayer = featureExtractorLayerArg
  }

  import org.deeplearning4j.datasets.iterator.AsyncDataSetIterator
  import org.deeplearning4j.nn.modelimport.keras.InvalidKerasConfigurationException
  import org.deeplearning4j.nn.modelimport.keras.UnsupportedKerasConfigurationException
  import org.nd4j.linalg.dataset.ExistingMiniBatchDataSetIterator
  import org.nd4j.linalg.dataset.api.iterator.DataSetIterator
  import java.io.IOException

  @throws(classOf[UnsupportedKerasConfigurationException])
  @throws(classOf[IOException])
  @throws(classOf[InvalidKerasConfigurationException])
  def trainIterator: DataSetIterator = {
    runFeaturize()
    val existingTrainingData = new ExistingMiniBatchDataSetIterator(new File("trainFolder"), "flowers-" + featureExtractorLayer + "-train-%d.bin")
    val asyncTrainIter = new AsyncDataSetIterator(existingTrainingData)
    asyncTrainIter
  }

  def testIterator: DataSetIterator = {
    val existingTestData = new ExistingMiniBatchDataSetIterator(new File("testFolder"), "flowers-" + featureExtractorLayer + "-test-%d.bin")
    val asyncTestIter = new AsyncDataSetIterator(existingTestData)
    asyncTestIter
  }

  @throws(classOf[UnsupportedKerasConfigurationException])
  @throws(classOf[IOException])
  @throws(classOf[InvalidKerasConfigurationException])
  private def runFeaturize() = {
    val trainDir = new File("trainFolder", "flowers-" + featureExtractorLayer + "-train-0.bin")
    if (!trainDir.isFile) {
      log.info("\n\tFEATURIZED DATA NOT FOUND. \n\t\tRUNNING \"FeaturizedPreSave\" first to do presave of featurized data")
      FeaturizedPreSave.main(null)
    }
  }
} 
开发者ID:endymecy,项目名称:dl4scala,代码行数:50,代码来源:FlowerDataSetIteratorFeaturized.scala


示例7: Application

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

import java.io.{IOException, InputStream}

import models.TheWord
import play.api._
import play.api.mvc._

import scala.collection.mutable

object Application extends Controller {

  implicit val app = Play.current

  def index = Action {
    val real = getThatText("sample1.txt")
    val result = doTheJobFun {
      mutable.Seq(real: _*)
    }
    Ok(views.html.index(real.mkString("\n"), result))

  }

  def test = Action {
    Ok(getThatText("sample1.txt").mkString("\n"))
  }

  def load(filePath: String): InputStream = {
    Play.resourceAsStream("public/inputs/" concat filePath).getOrElse(throw new IOException("file not found: " + filePath))
  }

  def getThatText(fileName: String) = {
    //    val source = scala.io.Source.fromFile(app.getFile(fileName))("UTF-8")
    val source = scala.io.Source.fromInputStream(load(fileName))("UTF-8")
    try source.getLines().toList
    catch {
      case e: Exception => e.printStackTrace(); null
    }
    finally source.close()
  }

  val doTheJobFun = (text: mutable.Seq[String]) => {
    text.flatMap(_.split("[.?!:]"))
      .map(_.split("\\s+").find(_.nonEmpty).getOrElse(""))
      .filter(_.matches("[a-zA-Z].*"))
      .filter(!_.equals(""))
      .map { p => TheWord(p, p.reverse) }
      .toList
  }

} 
开发者ID:muhrifqii,项目名称:learn-to-play-scala,代码行数:52,代码来源:Application.scala


示例8: NioClientEndPoint

//设置package包名称以及导入依赖的类
package knot.remote.endpoints

import java.io.IOException
import java.net.InetSocketAddress
import java.nio.channels.SelectionKey

import knot.remote.channel.{NioChannel, NioSocketChannel}

class NioClientEndPoint extends NioEndpoint {

  override def processKey(key: SelectionKey, channel: NioSocketChannel): Unit = {
    if (key.isConnectable) {
      if (!channel.finishConnect) throw new IOException("Connect Fail")
      val ops = key.interestOps() & ~SelectionKey.OP_CONNECT
      key.interestOps(ops)
      log.debug("CLIENT: Connected")
    }

    if (key.isReadable || key.readyOps() == 0) {
      channel.read()
    }
  }

  override def init(channel: NioChannel, address: InetSocketAddress): Unit = {
    channel.connect(address)
    channel.register(this, SelectionKey.OP_CONNECT)
  }
} 
开发者ID:defvar,项目名称:knot,代码行数:29,代码来源:NioClientEndPoint.scala


示例9: ErrorHandling

//设置package包名称以及导入依赖的类
package org.argus.jawa.compiler.compile.io

import java.io.IOException

object ErrorHandling
{
  def translate[T](msg: => String)(f: => T): T =
    try { f }
    catch {
      case e: IOException => throw new TranslatedIOException(msg + e.toString, e)
      case e: Exception => throw new TranslatedException(msg + e.toString, e)
    }

  def wideConvert[T](f: => T): Either[Throwable, T] =
    try { Right(f) }
    catch
    {
      case ex @ (_: Exception | _: StackOverflowError) => Left(ex)
      case err @ (_: ThreadDeath | _: VirtualMachineError) => throw err
      case x: Throwable => Left(x)
    }

  def convert[T](f: => T): Either[Exception, T] =
    try { Right(f) }
    catch { case e: Exception => Left(e) }

  def reducedToString(e: Throwable): String =
    if(e.getClass == classOf[RuntimeException])
    {
      val msg = e.getMessage
      if(msg == null || msg.isEmpty) e.toString else msg
    }
    else
      e.toString
}
sealed class TranslatedException private[io](msg: String, cause: Throwable) extends RuntimeException(msg, cause) {
  override def toString: String = msg
}
final class TranslatedIOException private[io](msg: String, cause: IOException) extends TranslatedException(msg, cause) 
开发者ID:arguslab,项目名称:Argus-SAF,代码行数:40,代码来源:ErrorHandling.scala


示例10: Converter

//设置package包名称以及导入依赖的类
package com.dataoptimo.imgprocessing.convert
import org.apache.hadoop.conf.Configuration
import org.apache.hadoop.io.Text
import org.apache.hadoop.io.BytesWritable
import org.apache.hadoop.fs.{Path, FileSystem}
import org.apache.hadoop.io.IOUtils
import org.apache.hadoop.io.SequenceFile
import java.io.IOException
import java.lang.IllegalArgumentException

class Converter(conf: Configuration) {
  
  def imageToSequence(srcPath: String, dstPath: String){
    try {
    val fs = FileSystem.get(conf);
    val inPath = new Path(srcPath);
    val outPath = new Path(dstPath);
    val key = new Text();
    val value = new BytesWritable();
    val in = fs.open(inPath);
    val buffer = new Array[Byte](in.available())
    in.read(buffer);
    var writer = SequenceFile.createWriter(fs, conf, outPath, key.getClass(),value.getClass());
    writer.append(new Text(inPath.getName()), new BytesWritable(buffer));
    IOUtils.closeStream(writer);
    }
    catch {
      case io: IOException => println(io.getMessage)
      case illegalArgument: IllegalArgumentException => println(illegalArgument.getMessage)
    }
    
    
    
  }
} 
开发者ID:mfawadalam,项目名称:imgprocessing,代码行数:36,代码来源:Converters.scala


示例11: EmbeddedKafka

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

import java.io.IOException
import java.nio.file._
import java.nio.file.attribute.BasicFileAttributes
import java.util.Properties

import akka.actor.Actor
import utils.embeddedkafka.KafkaLocal

class EmbeddedKafka extends Actor {

	var embeddedKafka: Option[KafkaLocal] = None

	override def preStart(): Unit = {
		super.preStart()
		deleteKafkaData()
		embeddedKafka = Some(initEmbeddedKafka())
		context.parent ! "Start"
	}

	override def postStop(): Unit = {
		embeddedKafka.foreach(_.stop())
		super.postStop()
	}

	def initEmbeddedKafka() = {
		val kafkaProperties = new Properties()
		val zkProperties = new Properties()
		kafkaProperties.load(getClass.getResourceAsStream("/kafkalocal.properties"))
		zkProperties.load(getClass.getResourceAsStream("/zklocal.properties"))
		new KafkaLocal(kafkaProperties, zkProperties)
	}

	override def receive: Actor.Receive = {
		case _ =>
	}

	def deleteKafkaData(): Unit = {
		val path = Paths.get("./data")
		Files.walkFileTree(path, new FileVisitor[Path] {
			override def visitFileFailed(file: Path, exc: IOException) = FileVisitResult.CONTINUE

			override def visitFile(file: Path, attrs: BasicFileAttributes) = {
				Files.delete(file)
				FileVisitResult.CONTINUE
			}

			override def preVisitDirectory(dir: Path, attrs: BasicFileAttributes) = FileVisitResult.CONTINUE

			override def postVisitDirectory(dir: Path, exc: IOException) = {
				Files.delete(dir)
				FileVisitResult.CONTINUE
			}
		})
	}
} 
开发者ID:jw3,项目名称:example-kafka-tweets,代码行数:58,代码来源:EmbeddedKafka.scala


示例12: userToString

//设置package包名称以及导入依赖的类
package de.hsrm.cs.kochplattformweb.printer

import de.hsrm.cs.kochplattformweb.client.AbstractUser
import de.hsrm.cs.kochplattformweb.utils.SWTLogger
import java.io.FileWriter
import java.io.IOException
import java.util
import javax.xml.transform.Transformer


	def userToString(user:AbstractUser):String= {
		if(user.isAdmin) return "Admin"
		"MainUser"
	}
	@Override
	def setParameters(transformer: Transformer, out:FileWriter) {
		val res:StringBuffer = new StringBuffer(1024)
		res.append("<list>")
		val iter:java.util.Iterator[AbstractUser]=this.userlist.iterator()
		while (iter.hasNext) {
			var i:AbstractUser=iter.next()
			res.append("<item><name>")
			res.append(i.name)
			res.append("</name><position>")
			res.append(this.userToString(i))
			res.append("</position><password>")
			res.append(i.password)
			res.append("</password><id>")
			res.append(Printer.formatBigInteger(i.id))
			res.append("</id></item>")
		}
		res.append("</list>")
		try {
			out.append(res)
			out.append("</userlist>")
			out.close()
		} catch {
			case e:IOException =>SWTLogger.writeerror(e.getMessage)
		}
	}
} 
开发者ID:situx,项目名称:KochplattformWeb,代码行数:42,代码来源:PrintUserList.scala


示例13: PrintAdmin

//设置package包名称以及导入依赖的类
package de.hsrm.cs.kochplattformweb.printer

import java.io.FileWriter
import java.io.IOException
import javax.xml.transform.Transformer

import de.hsrm.cs.kochplattformweb.client.Admin
import de.hsrm.cs.kochplattformweb.utils.SWTLogger


class PrintAdmin(admin:Admin) extends Parameterable {

	@Override
	override def setParameters(transformer: Transformer,out:FileWriter) {
		transformer.setParameter("name", this.admin.name)
		transformer.setParameter("password", this.admin.password)
		transformer.setParameter("id", Printer.formatBigInteger(this.admin.id))
		try {
			out.append("</admin>")
			out.close()
		} catch{
			case e:IOException => SWTLogger.writeerror(e.getMessage)
		} 
	}
} 
开发者ID:situx,项目名称:KochplattformWeb,代码行数:26,代码来源:PrintAdmin.scala


示例14: PrintMessage

//设置package包名称以及导入依赖的类
package de.hsrm.cs.kochplattformweb.printer

import java.io.FileWriter
import java.io.IOException
import javax.xml.transform.Transformer

import de.hsrm.cs.kochplattformweb.utils.SWTLogger


class PrintMessage(message:String) extends Parameterable {

	@Override
	def setParameters(transformer:Transformer, out:FileWriter) {
		transformer.setParameter("text", this.message)
		try {
			out.append("</message>")
			out.close();
		} catch {
			case e:IOException =>SWTLogger.writeerror(e.getMessage)
		}
	}
} 
开发者ID:situx,项目名称:KochplattformWeb,代码行数:23,代码来源:PrintMessage.scala


示例15: setParameters

//设置package包名称以及导入依赖的类
package de.hsrm.cs.kochplattformweb.printer

import java.io.FileWriter
import java.io.IOException
import javax.xml.transform.Transformer

import de.hsrm.cs.kochplattformweb.db.{Ingredient, RecipeEntry}
import de.hsrm.cs.kochplattformweb.utils.SWTLogger


	var count:Int=0

	@Override
	override def setParameters(transformer:Transformer, out:FileWriter) {
		val res: StringBuffer = new StringBuffer(1024)
		res.append("<list>")
		for (i:RecipeEntry<-this.rlist) {
			res.append("<item><name>")
			res.append(i.name)
			res.append("</name><category>")
			res.append(i.category)
			res.append("</category><time>")
			res.append(i.time)
			res.append("</time><rating>")
			res.append(Printer.formatDouble(i.rating))
			res.append("</rating><ingredient>")
			this.count = 0
			for (intgre:Ingredient <- i.ingredients) {
				if(this.count == i.ingredients
						.size-1) {
					res.append(intgre
							.name)
				}
				else {
					res.append(intgre
							.name)
					res.append(", ")
				}
				this.count+=1
			}
			res.append("</ingredient></item>")
		}
		try {
			out.append(res)
			out.append("</list></recipeentry>")
			out.close()
		} catch { case e:IOException =>	SWTLogger.writeerror(e.getMessage)
		}
	}

} 
开发者ID:situx,项目名称:KochplattformWeb,代码行数:52,代码来源:PrintRecipeEntryList.scala


示例16: PrintUser

//设置package包名称以及导入依赖的类
package de.hsrm.cs.kochplattformweb.printer

import java.io.FileWriter
import java.io.IOException
import javax.xml.transform.Transformer

import de.hsrm.cs.kochplattformweb.client.MainUser
import de.hsrm.cs.kochplattformweb.utils.SWTLogger


class PrintUser(user:MainUser) extends Parameterable {

	@Override
	override def setParameters(transformer:Transformer, out:FileWriter) {
		transformer.setParameter("name", this.user.name)
		transformer.setParameter("password", this.user.password)
		transformer.setParameter("id", Printer.formatBigInteger(this.user.id))
		try {
			out.append("</user>")
			out.close()
		} catch{
			case e:IOException => SWTLogger.writeerror(e.getMessage)
		}
	}
} 
开发者ID:situx,项目名称:KochplattformWeb,代码行数:26,代码来源:PrintUser.scala


示例17: SDS

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

import java.io.{IOException, File};
import java.util.jar.JarFile;
import scala.collection.mutable.ArrayBuffer;
import sds.util.{ClassfilePrinter => Printer}

class SDS(args: Array[String]) {
    var jar: JarFile = null;
    val classfiles: ArrayBuffer[String] = ArrayBuffer()
    args.foreach(parseArgs)

    private def parseArgs(arg: String): Unit = {
        if(arg.endsWith(".class")) {
            classfiles += arg
        } else if(arg.endsWith(".jar")) {
            try {
                this.jar = new JarFile(new File(arg))
            } catch {
                case e: IOException => e.printStackTrace()
            }
        } else {
            println(arg + " is not classfile or jar.")
        }
    }

    private def analyzeClassfile(): Unit = {
        classfiles.foreach((file: String) => {
            val reader: ClassfileReader = new ClassfileReader(file)
            val classfile: Classfile = reader.classfile
            val p: Printer = new Printer(classfile)
            p._print
        })
    }

    def run(): Unit = {
        if(classfiles.nonEmpty) analyzeClassfile()
        if(jar != null) println("")
    }
} 
开发者ID:g1144146,项目名称:sds_for_scala,代码行数:41,代码来源:SDS.scala


示例18: Extractor

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

import java.io.File
import java.io.IOException
import utils.Status._
import scala.sys.process._

object Extractor {
    
    
    def completeDirectoryPath(path: String) = {
        if (path.endsWith("/")) path
        else path + "/"
    }
    
    def createDirectory(directoryPath: String): Status = {
        val directory = new File(directoryPath)
        if(directory.exists && !directory.isDirectory)
            return DIRECTORY_FILE_COLLISION.withArgument(directoryPath)
        
        try {
            directory.mkdir()
            return OK
        }
        catch {
            case se: SecurityException  => return SECURITY_ERROR.withArgument(se) 
            case ioe: IOException       => return IO_ERROR.withArgument(ioe)  
            case e: Exception           => return UNKNOWN_ERROR.withArgument(e)
        }
    }
    
    def executeCommand(cmd: String): (Status, String) = {
        val result = cmd.!!
        return (OK, result)
    }
    
    def extractLines(file: File) = {
        val source = scala.io.Source.fromFile(file.getPath)
        val lines = try source.mkString finally source.close()
        lines
    }
    def extractArchive(archivePath: String, extractionDirectory: String) = {
        val cmd = "tar -xvf " + archivePath + " -C " + extractionDirectory
        val (status, result) = executeCommand(cmd)
        if (status.isBad)
            status
        else
            OK
    }
    
    def extractArchiveRSync(archivePath: String, extractionDirectory: String) = {
        val cmd = "rsync -aHSx --no-devices --no-specials " + archivePath + " " + extractionDirectory
        val (status, result) = executeCommand(cmd)
        if (status.isBad)
            status
        else
            OK
    }
} 
开发者ID:vincenthage,项目名称:proot-oci-loader,代码行数:60,代码来源:extractor.scala


示例19: fromResource

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

import java.io.IOException

import scala.io.Source


  def fromResource(fileName: String): String = {
    import resource._
    val res = managed(getClass.getClassLoader.getResourceAsStream(fileName))
      .map {
        inputStream =>
          if (inputStream == null)
            throw new IOException("File not found: " + fileName)
          val template = Source.fromInputStream(inputStream).mkString
          template
      }.either.either
    res match {
      case Left(throwables) => throw throwables.head
      case Right(string) => string
    }
  }
} 
开发者ID:krish121,项目名称:Spark-reference-applications,代码行数:24,代码来源:TemplateProvider.scala


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



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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