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


Scala FileNotFoundException类代码示例

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


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

示例1: UtilSpec

//设置package包名称以及导入依赖的类
package tech.artemisia.util

import java.io.{File, FileNotFoundException}
import tech.artemisia.TestSpec
import tech.artemisia.core.Keywords.Config
import tech.artemisia.core.TestEnv.TestOsUtil
import tech.artemisia.core.{Keywords, env}




class UtilSpec extends TestSpec {

  var os_util: TestOsUtil = _

  override def beforeEach(): Unit = {
    super.beforeEach()
    os_util = env.osUtil.asInstanceOf[TestOsUtil]
  }

  "The Util.readConfigFile" must "throw FileNotFoundException on non-existent file" in {
    intercept[FileNotFoundException] {
      Util.readConfigFile(new File("Some_Non_Existant_File.conf"))
    }
  }

  "Util.getGlobalConfigFileLocation" must s"must provide default value when is ${Config.GLOBAL_FILE_REF_VAR} not set" in {
    os_util.withSysVar(Map()) {
      val default_value = this.getClass.getResource("/code/code_with_simple_mysql_component.conf").getFile
      Util.getGlobalConfigFileLocation(default_value).get must equal(default_value)
    }
  }

  it must s"must give a None if ${Keywords.Config.GLOBAL_FILE_REF_VAR} not set and the default file doesn't exist" in {
    os_util.withSysVar(Map("foo2" -> "baz2")) {
      val default_value = "A_Non_Existant_File.conf"
      Util.getGlobalConfigFileLocation(default_value) must equal(None)
    }
  }

} 
开发者ID:gitter-badger,项目名称:artemisia,代码行数:42,代码来源:UtilSpec.scala

示例2: TipConfig

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

import java.io.FileNotFoundException

import com.typesafe.config.{Config, ConfigFactory}
import net.ceedubs.ficus.Ficus._
import net.ceedubs.ficus.readers.ArbitraryTypeReader._
import net.jcazevedo.moultingyaml._
import scala.util.Try
import scala.io.Source.fromFile

// $COVERAGE-OFF$

case class TipConfig(owner: String, repo: String, personalAccessToken: String, label: String)

class TipConfigurationException(msg: String = "Missing TiP config. Please refer to README.") extends RuntimeException(msg)
class MissingPathConfigurationFile(msg: String = "Missing tip.yaml. Please refer to README") extends RuntimeException(msg)
class PathConfigurationSyntaxError(msg: String = "Bad syntax in tip.yaml. Please refer to README") extends RuntimeException(msg)

object Configuration {
  object TipYamlProtocol extends DefaultYamlProtocol { implicit val pathFormat = yamlFormat2(Path) }

  import TipYamlProtocol._

  val config: Config = ConfigFactory.load()
  val tipConfig = config.as[Option[TipConfig]]("tip").getOrElse(throw new TipConfigurationException)

  def readFile(filename: String): String =
    Option(getClass.getClassLoader.getResource(filename)).map {
      path => fromFile(path.getPath).mkString
    }.getOrElse(throw new FileNotFoundException(s"Path definition file not found on the classpath: $filename"))

  def readPaths(filename: String): List[Path] = Try(readFile(filename).parseYaml.convertTo[List[Path]]).recover {
    case e: FileNotFoundException => throw new MissingPathConfigurationFile
    case _ => throw new PathConfigurationSyntaxError
  }.get
}

// $COVERAGE-ON$ 
开发者ID:guardian,项目名称:tip,代码行数:40,代码来源:Configuration.scala

示例3: Shader

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

import java.io.FileNotFoundException

import com.badlogic.gdx.graphics.glutils.ShaderProgram
import com.github.gigurra.glasciia.impl.LoadFile


object Shader {

  def fromLocation(vertexShader: String, fragmentShader: String): ShaderProgram = {
    fromSourceCode(
      LoadFile(vertexShader).getOrElse(throw new FileNotFoundException(s"Could not find vertex shader source file '$vertexShader'")).readString(),
      LoadFile(fragmentShader).getOrElse(throw new FileNotFoundException(s"Could not find fragment shader source file '$fragmentShader'")).readString()
    )
  }

  def fromSourceCode(vertexShader: String, fragmentShader: String): ShaderProgram = {
    val out = new ShaderProgram(vertexShader, fragmentShader)
    if (!out.isCompiled)
      throw new IllegalArgumentException(s"Compilation of shader failed!: ${out.getLog}")
    out
  }
} 
开发者ID:GiGurra,项目名称:glasciia,代码行数:25,代码来源:Shader.scala

示例4: TryCatch

//设置package包名称以及导入依赖的类
package com.chapter3.ScalaFP
import java.io.IOException
import java.io.FileReader
import java.io.FileNotFoundException
object TryCatch {
  def main(args: Array[String]) {
    try {
      val f = new FileReader("data/data.txt")
    } catch {
      case ex: FileNotFoundException => println("File not found exception")
      case ex: IOException => println("IO Exception") 
    } finally {
      println("Finally block always executes");
    }
  }
} 
开发者ID:PacktPublishing,项目名称:Scala-and-Spark-for-Big-Data-Analytics,代码行数:17,代码来源:TryCatchFinally.scala

示例5: Url

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

import java.io.FileNotFoundException
import java.lang.Thread.currentThread
import java.net.URL

object Url {
  def apply(path: String): URL =
    Option(
      currentThread()
        .getContextClassLoader
        .getResource(path)
    ) match {
      case Some(url) ? url
      case None ?
        throw new FileNotFoundException(
          s"Test resource not found: $path"
        )
    }
} 
开发者ID:hammerlab,项目名称:test-utils,代码行数:21,代码来源:Url.scala

示例6: ResourcesTest

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

import java.io.FileNotFoundException
import org.hammerlab.test.Suite

class ResourcesTest extends Suite {
  test("non-existent url") {
    intercept[FileNotFoundException] {
      Url("foo")
    }
  }

  test("non-existent file") {
    intercept[FileNotFoundException] {
      File("foo")
    }
  }

  test("read file") {
    File("a/numbers").read should be(
      """1
        |2
        |3
        |"""
      .stripMargin
    )
  }

  test("read file bytes") {
    File("a/numbers").readBytes should be(
      """1
        |2
        |3
        |"""
      .stripMargin
      .getBytes
    )
  }
} 
开发者ID:hammerlab,项目名称:test-utils,代码行数:40,代码来源:ResourcesTest.scala

示例7: ExceptionUtils

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

import java.io.FileNotFoundException
import java.io.IOException
import java.io.FileReader

object ExceptionUtils {

  def main(args: Array[String]) {

    try {
      val f = new FileReader("input.txt")
    } catch {
      case ex: FileNotFoundException => {
        println("FileNotFoundException"+ex.getMessage)
      }
      case ex: IOException => {
        println("IOException")
      }
    }finally{  //finally ?????????????????????????????
      println("?????????????")
    }
    
    
  }
  
   def matchTest(x: Int){
      x match{
        case 1 if x<=4 => println("one")
        case 2 => println("two")
        //case _x => println("age"+_x)
        case _ => println("many")
      }
      
   }
  
} 
开发者ID:jacktomcat,项目名称:scala-practice,代码行数:38,代码来源:ExceptionUtils.scala

示例8: ReadFromFileTest

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

import model.PSP1List
import org.scalatest.Matchers._
import org.scalatest.WordSpec


class ReadFromFileTest extends WordSpec {
  val emptyFileName: String = getClass.getResource("testEmpty.txt").getFile
  val testFileName: String = getClass.getResource("test.txt").getFile
  val fileWithWrongFormat: String = getClass.getResource("fileWithWrongFormat.txt").getFile

  "A read file" when {
    "it is not found" should {
      "throw a FileNotFoundException" in {
        intercept[FileNotFoundException](ReadFromFile.getListFromFile("aowjdoaiwjdoaiwjdoaiwjdoaiwjdoaiwjdo"))
      }
    }
    "it is empty" should {
      "return an empty list" in {
        assert(ReadFromFile.getListFromFile(emptyFileName).isEmpty)
      }
    }
    "has numbers" should {
      val result = ReadFromFile.getListFromFile(testFileName)
      "return its content as a PSP1List" in {
        result shouldBe an[PSP1List]
      }
      "return its content as a non-empty List" in {
        assert(result.nonEmpty)
      }
      "its content should match to the expected ones" in {
        result.list match {
          case 160.0 :: 15.0 :: (-15.0) :: Nil => succeed
          case _ => fail
        }
      }
    }
    "has a wrong format" should {
      "throw a NumberFormatException" in {
        intercept[NumberFormatException](ReadFromFile.getListFromFile(fileWithWrongFormat))
      }
    }
  }
} 
开发者ID:camilosampedro,项目名称:PSP-TDD,代码行数:46,代码来源:ReadFromFileTest.scala

示例9: ReadFromFileTest

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

import model.PSP1List
import org.scalatest.Matchers._
import org.scalatest.WordSpec


class ReadFromFileTest extends WordSpec {
  val emptyFileName: String = getClass.getResource("testEmpty.txt").getFile
  val testFileName: String = getClass.getResource("test.txt").getFile
  val fileWithWrongFormat: String = getClass.getResource("fileWithWrongFormat.txt").getFile

  "A read file" when {
    "it is not found" should {
      "throw a FileNotFoundException" in {
        intercept[FileNotFoundException](ReadFromFile.getListFromFile("aowjdoaiwjdoaiwjdoaiwjdoaiwjdoaiwjdo"))
      }
    }
    "it is empty" should {
      "return an empty list" in {
        assert(ReadFromFile.getListFromFile(emptyFileName).isEmpty)
      }
    }
    "has numbers" should {
      val result = ReadFromFile.getListFromFile(testFileName)
      "return its content as a PSP1List" in {
        result shouldBe an[PSP1List]
      }
      "return its content as a non-empty List" in {
        assert(result.nonEmpty)
      }
      "its content should match to the expected ones" in {
        result.list match {
          case Vector(160.0, 15.0, -15.0) => succeed
          case _ => fail
        }
      }
    }
    "has a wrong format" should {
      "throw a NumberFormatException" in {
        intercept[NumberFormatException](ReadFromFile.getListFromFile(fileWithWrongFormat))
      }
    }
  }
} 
开发者ID:camilosampedro,项目名称:PSP-TDD,代码行数:46,代码来源:ReadFromFileTest.scala

示例10: LockingStorages

//设置package包名称以及导入依赖的类
package gv.jleon
package domain

import java.io.{ FileNotFoundException }
import java.nio.file.{ FileAlreadyExistsException }

object LockingStorages {

  final type Underlying = Storage

  final case class Locked(uri: Uri, cause: Throwable) extends Exception(s"locked: $uri", cause)

  trait Ops extends Any {

    def self: Underlying

    final def lockPath(uri: Uri): Storage.Path =
      self storagePathWithExt (uri, "lock")

    final def lock(uri: Uri): Try[WritableByteChannel] = {
      File.createNew(lockPath(uri))
        .recoverWith {
          case cause: FileAlreadyExistsException ?
            Failure(Locked(uri, cause))
        }
    }

    final def isLocked(uri: Uri): Boolean =
      File exists lockPath(uri)

    final def unlock(uri: Uri): Try[Unit] =
      if (File.delete(lockPath(uri)))
        Success {}
      else
        Failure {
          new FileNotFoundException(s"$uri - ${lockPath(uri)}")
        }
  }

} 
开发者ID:mouchtaris,项目名称:jleon,代码行数:41,代码来源:LockingStorages.scala

示例11: ScriptManager

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

import java.io.FileNotFoundException

import com.badlogic.gdx.Gdx
import com.badlogic.gdx.assets.loaders.FileHandleResolver
import com.badlogic.gdx.assets.loaders.resolvers.InternalFileHandleResolver
import org.luaj.vm2.LuaError
import org.luaj.vm2.lib.jse.JsePlatform

object ScriptManager {
  private val TAG = getClass.getSimpleName
  private val globals = JsePlatform.standardGlobals()

  def run(fileName: String): Unit = run(fileName, new InternalFileHandleResolver)

  def run(fileName: String, resolver: FileHandleResolver) = {
    val file = resolver.resolve(fileName)

    try {
      if (!file.exists) throw new FileNotFoundException

      val chunk = globals.load(file.readString())
      val luaValue = chunk.call()

      println(luaValue.toString)
    }
    catch {
      case ex: FileNotFoundException => Gdx.app.error(TAG, "Could not load Lua script <" + file.name + ">", ex)
      case ex: LuaError => Gdx.app.error(TAG, "Error running Lua script <" + file.name + ">", ex)
    }
  }
} 
开发者ID:starfleetcadet75,项目名称:RpgGame,代码行数:34,代码来源:ScriptManager.scala

示例12: ScannerSpec

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

import java.io.{FileNotFoundException, IOException}

import org.specs2._

import scala.collection.immutable.SortedSet

class ScannerSpec extends mutable.Specification {

  case class MockFilesystem(directories: Map[Directory, List[FilePath]], fileSizes: Map[File, Long]) extends Filesystem {

    def length(file: File) = fileSizes.getOrElse(file, throw new IOException())

    def listFiles(directory: Directory) =
      directories.getOrElse(directory, throw new FileNotFoundException(directory.path))
  }

  "Report Format" ! {
    val base = Directory("base")
    val base1 = File(s"${base.path}/1.txt")
    val base2 = File(s"${base.path}/2.txt")
    val subdir = Directory(s"${base.path}/subdir")
    val sub1 = File(s"${subdir.path}/1.txt")
    val sub3 = File(s"${subdir.path}/3.txt")
    val fs = MockFilesystem(
      Map(
        base -> List(subdir, base1, base2),
        subdir -> List(sub1, sub3)
      ),
      Map(base1 -> 1, base2 -> 2, sub1 -> 1, sub3 -> 3)
    )

    val actual = Scanner.pathScan(base, 2, fs)
    val expected = Right(new PathScan(SortedSet(FileSize(sub3, 3), FileSize(base2, 2)), 7, 4))

    actual.mustEqual(expected)
  }

  "Error handling" ! {
    val base = Directory("base")
    val fs = MockFilesystem(Map.empty, Map.empty)

    val actual = Scanner.pathScan(base, 2, fs)
    val expected = ???

    //Cant directly compare 2 different FileNotFoundException instances for equality, so convert to Strings first
    actual.toString.mustEqual(expected.toString)
  }

} 
开发者ID:benhutchison,项目名称:GettingWorkDoneWithExtensibleEffects,代码行数:52,代码来源:ScannerSpec.scala

示例13: ScannerSpec

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

import java.io.{FileNotFoundException, IOException}

import org.specs2._

import scala.collection.immutable.SortedSet

class ScannerSpec extends mutable.Specification {

  case class MockFilesystem(directories: Map[Directory, List[FilePath]], fileSizes: Map[File, Long]) extends Filesystem {

    def length(file: File) = fileSizes.getOrElse(file, throw new IOException())

    def listFiles(directory: Directory) =
      directories.getOrElse(directory, throw new FileNotFoundException(directory.path))
  }

  "Report Format" ! {
    val base = Directory("base")
    val base1 = File(s"${base.path}/1.txt")
    val base2 = File(s"${base.path}/2.txt")
    val subdir = Directory(s"${base.path}/subdir")
    val sub1 = File(s"${subdir.path}/1.txt")
    val sub3 = File(s"${subdir.path}/3.txt")
    val fs = MockFilesystem(
      Map(
        base -> List(subdir, base1, base2),
        subdir -> List(sub1, sub3)
      ),
      Map(base1 -> 1, base2 -> 2, sub1 -> 1, sub3 -> 3)
    )

    val actual = Scanner.pathScan(base, 2, fs)
    val expected = Right(new PathScan(SortedSet(FileSize(sub3, 3), FileSize(base2, 2)), 7, 4))

    actual.mustEqual(expected)
  }

  "Error handling" ! {
    val base = Directory("base")
    val fs = MockFilesystem(Map.empty, Map.empty)

    val actual = Scanner.pathScan(base, 2, fs)
    val expected = Left(new FileNotFoundException("base"))

    //Cant directly compare 2 different FileNotFoundException instances for equality, so convert to Strings first
    actual.toString.mustEqual(expected.toString)
  }

} 
开发者ID:benhutchison,项目名称:GettingWorkDoneWithExtensibleEffects,代码行数:52,代码来源:ScannerSpec.scala

示例14: ResourceLoader

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

import cats._
import cats.data._
import cats.implicits._

import scodec.bits._

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

#+desktop
object ResourceLoader {

  def loadFile(name: String): Xor[FileNotFoundException, BitVector] =
    try {
      val stream: InputStream = new FileInputStream(name)
      val r = BitVector.fromInputStream(stream).force
      stream.close()
      r.right
    } catch {
      case e: FileNotFoundException => e.left
    }
}
#-desktop

#+android
import android.content.res.Resources

object ResourceLoader {

  var resources: Resources = _

  def loadFile(name: String): Xor[FileNotFoundException, BitVector] =
    try {
      val stream: InputStream = resources.getAssets().open(name)
      val r = BitVector.fromInputStream(stream).force
      println(s"bitvector is ${r}")
      stream.close()
      r.right
    } catch {
      case e: FileNotFoundException => e.left
    }
}
#-android 
开发者ID:to-ithaca,项目名称:iliad,代码行数:45,代码来源:file.scala

示例15: PetstoreExampleSpec

//设置package包名称以及导入依赖的类
package io.gloriousfuture.openapi.v2.circe

import java.io.FileNotFoundException

import cats.syntax.either._
import cats.syntax.show._
import io.circe.Json
import io.circe.optics.JsonPath.root
import io.circe.parser.parse
import io.gloriousfuture.genrpc.openapi.v2.Root
import org.scalatest.{Matchers, WordSpec}

import scala.io.Source
import scala.reflect.ClassTag

class PetstoreExampleSpec extends WordSpec with Matchers {

  import CirceFormats._

  object ExampleJson {
    val petstore: Json = {
      val petstoreExample = Option(getClass.getResource("/petstore.json")) getOrElse {
        throw new FileNotFoundException("Could not find resource /petstore.json")
      }
      parse(Source.fromURL(petstoreExample).mkString).valueOr(throw _)
    }
  }

  def typeName[T](implicit clsTag: ClassTag[T]): String = s"openapi.v2.${clsTag.runtimeClass.getSimpleName}"

  "petstore.json" should {

    s"parse as ${typeName[Root]}" in {
      val result = ExampleJson.petstore.as[Root].valueOr(e => fail(e.show))
      assert(result.info.title contains "Petstore")
      val petModelTypeName = result.definitions.get("Pet").properties("name").asPrimitive.get.`type`
      assertResult("string")(petModelTypeName)
    }

    s"read tags field from ${typeName[Root]}" in {
      val tags = root.tags.each.name.string.getAll(ExampleJson.petstore)
      tags should contain theSameElementsAs Seq("pet", "store", "user")
    }
  }
} 
开发者ID:gloriousfutureio,项目名称:genspec-openapi,代码行数:46,代码来源:PetstoreExampleSpec.scala


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