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


Scala File类代码示例

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


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

示例1: LocalFileUtil

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

import scala.reflect.io.File


object LocalFileUtil {

  def isDirectoryExists(directory: String): Boolean = {
    val dir = File(directory)
    if (dir.isDirectory) true else false
  }

  def isFileExists(fileName: String): Boolean = {
    val file = File(fileName)
    if (file.isFile && file.exists) true else false
  }

  def deleteFile(fileName: String): Unit = {
    val file = File(fileName)
    if (file.isFile && file.exists) {
      file.delete()
    }
  }

  def deleteDirectory(directory: String): Unit = {
    val dir = File(directory)
    if (dir.isDirectory && dir.exists) {
      dir.deleteRecursively()
    }
  }

  def deleteFileWithPath(path: String): Boolean = {
    val file = File(path)
    if (file.isDirectory) {
      file.deleteRecursively()
    } else {
      file.delete()
    }
  }

} 
开发者ID:youzp,项目名称:spark-utils,代码行数:42,代码来源:LocalFileUtil.scala

示例2: Config

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

import xsbti.{ AppConfiguration, MainResult }
import scala.reflect.io.File


case class Config(variablesFile: File = File("variables"), templateDirectory: File = File("templates"))

class Exit(val code: Int) extends xsbti.Exit

class OreOreTemplate extends xsbti.AppMain {
  override def run(appConfiguration: AppConfiguration): MainResult = new Exit(run(appConfiguration.arguments()))

  def run(args: Array[String]): Int = {
    args.partition { s ?
      s.matches("""""")
    }
    println("hoge")
    0
  }

}

object OreOreTemplate {
  val parser = new scopt.OptionParser[Config]("oreoretemplate") {
    head("oretmpl", "0.1.0")
  }
} 
开发者ID:NomadBlacky,项目名称:oreore-template-scala,代码行数:29,代码来源:OreOreTemplate.scala

示例3: ScannerPrint

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

import java.util.Scanner

import scala.reflect.io.File
import scala.reflect.io.Path.string2path

object ScannerPrint {
  def main(args: Array[String]): Unit = {
      //object is like singleton object of a class defined implicitly.
      ScannerPrint.withScan(File("src/main/resources/scanfile.properties"),
        scanner => println("pid is " + scanner.next()))
      
      //throw exception
      ScannerPrint.withScan(File("src/main/resources/scanfile.properties"),
      scanner => log("pid is " + scanner.next() + 1/0))
      
      //call By Name  don't throw exception, , evaluate until execute 
      ScannerPrint.withScan(File("src/main/resources/scanfile.properties"),
      scanner => logByName("pid is " + scanner.next() + 1/0))
  }

  def withScan(f: File, op: Scanner => Unit) {
    val scanner = new Scanner(f.bufferedReader())
    try {
      op(scanner)
    } finally {
      scanner.close()
    }
  }
  val logEnable = false
  
  def log(msg:String) = if(logEnable) println(msg)
  //call by name
  def logByName(msg: =>String) = if(logEnable) println(msg)

} 
开发者ID:Chehao,项目名称:Akkala,代码行数:38,代码来源:ScannerPrint.scala

示例4: WordCounter

//设置package包名称以及导入依赖的类
import scala.io.Codec.string2codec
import scala.io.Source
import scala.reflect.io.File

object WordCounter {
    val SrcDestination: String = ".." + File.separator + "file.txt"
    val Word = "\\b([A-Za-z\\-])+\\b".r

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

        val counter = Source.fromFile(SrcDestination)("UTF-8")
                .getLines
                .map(l => Word.findAllIn(l.toLowerCase()).toSeq)
                .toStream
                .groupBy(identity)
                .mapValues(_.length)

        println(counter)
    }
} 
开发者ID:nil68657,项目名称:SparkWordCount-Scala,代码行数:21,代码来源:SparkWordCount.scala

示例5: VerifiableFileSpec

//设置package包名称以及导入依赖的类
package org.plunderknowledge.sumcrawler.model.test

import org.specs2.mutable.Specification
import org.plunderknowledge.sumcrawler.model.VerifiableFile

import scala.reflect.io.File
import scala.util.Random
import com.roundeights.hasher.Implicits._
import org.specs2.specification.BeforeAll
import scalikejdbc._
import scalikejdbc.config._
import scalikejdbc.specs2.mutable.AutoRollback

import org.flywaydb.core.Flyway



class VerifiableFileSpec extends Specification with BeforeAll {

  override def beforeAll(): Unit = {
    DBsWithEnv("test").setupAll()
    val flyway = new Flyway()
    flyway.setDataSource(ConnectionPool.dataSource('default))
    flyway.migrate()
  }

  sequential

  "Verifiable file should correctly identify correct sums" in new AutoRollback {
    val verifiable = VerifiableFile(VerifiableFileSpec.correctFileUrl, VerifiableFileSpec.correctFileSum, "md5", None)
    verifiable.verify() must beTrue
    sql"""select count(*) as success_count from signature
          where success = true""".map(rs => rs.int("success_count")).single.apply() must beEqualTo(Some(1))
  }
}

object VerifiableFileSpec {

  def kestrel[A](x: A)(f: A => Unit): A = { f(x); x }

  def writeFile(bytes: Array[Byte]): String = {
    val f = File.makeTemp()
    f.outputStream().write(bytes)
    f.toAbsolute.path
  }

  val correctFileBytes = kestrel(Array.fill[Byte](200)(0))(Random.nextBytes)
  val tempFileName = writeFile(correctFileBytes)
  val correctFileSum = correctFileBytes.md5.hex
  val correctFileUrl = s"file://${tempFileName}"

} 
开发者ID:PlunderKnowledge,项目名称:SumCrawler,代码行数:53,代码来源:VerifiableFileSpec.scala

示例6: Main

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

import configuration._

import scala.io.StdIn
import scala.reflect.io.File

object Main extends App {

  val configFile = "lockStepConfigFile"
  File(configFile).createFile(failIfExists = false)
  println("Hello and welcome to LockStep")

  LockStepArgs.parse(args = args, LockStepArgsConfig()) match {
    case Some(config) => exeucuteConfig(config = config)
    case None => displayErrorMessage()
  }

  private def exeucuteConfig(config:LockStepArgsConfig) = config match {
    case LockStepArgsConfig(true, setup, run) => displayHelp()
    case LockStepArgsConfig(false, true, run) => setup()
    case LockStepArgsConfig(false, false, true) => run()
    case _ => displayErrorMessage()
  }

  private def setup(): Unit = {
    print("Please enter localDir:")
    val localDir = StdIn.readLine()

    print("Please enter remote directory:")
    val remoteDir = StdIn.readLine()

    print("Please add remote server location:")
    val remoteServerLocation = StdIn.readLine()

    LockStepConfigurationManager(configFile).storeLockStepConfigurationEntry(localDir,
      RemoteLocation(remoteDir, remoteServerLocation))
  }

  private def run() : Unit = {
    LockStepActorSystem(LockStepConfigurationManager(configFile))
  }

  private def displayHelp() : Unit = {
    println("TODO : Write down Help")
  }

  private def displayErrorMessage() : Unit = {
    println("TODO: Write down display error message")
  }
} 
开发者ID:Khalian,项目名称:LockStep,代码行数:52,代码来源:Main.scala

示例7: ConfigurationSpec

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

import configuration.{LockStepConfiguration, LockStepConfigurationManager, RemoteLocation}
import org.scalatest.{BeforeAndAfter, FlatSpec}

import scala.reflect.io.File

class ConfigurationSpec extends FlatSpec with BeforeAndAfter {

  val testConfigFile:String = "TEST_CONFIG_FILE"
  val testLocalDir:String = "fooLocalDir"
  val testRemoteDir:String = "fooRemoteDir"
  val testRemoteAddr:String = "fooRemoteAddr"

  before {
    File(testConfigFile).createFile(failIfExists = true)
  }

  after {
    File(testConfigFile).delete()
  }

  "A LockStepConfigurationManager" should "be able to add and retrieve " +
    "configuration items in config file" in {
    val configMgr = LockStepConfigurationManager(testConfigFile)
    configMgr.storeLockStepConfigurationEntry(testLocalDir,
      RemoteLocation(testRemoteDir, testRemoteAddr))

    val lockStepConfig = configMgr.readLockStepConfigurationFile()
    assertResult(lockStepConfig.getRemoteDir(testLocalDir))(testRemoteDir)
    assertResult(lockStepConfig.getRemoteServerAddr(testLocalDir))(testRemoteAddr)
  }

  "A LockStepConfiguration" should "not break on getting invalid configs" in {
    val lockStepConfig = LockStepConfiguration()

    assertThrows[NoSuchElementException] {
      lockStepConfig.getRemoteDir(testLocalDir)
    }

    assertThrows[NoSuchElementException] {
      lockStepConfig.getRemoteServerAddr(testLocalDir)
    }
  }
} 
开发者ID:Khalian,项目名称:LockStep,代码行数:46,代码来源:ConfigurationSpec.scala

示例8: Configuration

//设置package包名称以及导入依赖的类
// Copyright (c) Microsoft. All rights reserved.

package it.helpers

import java.nio.file.{Files, Paths}

import com.microsoft.azure.eventhubs.EventHubClient
import com.typesafe.config.{Config, ConfigFactory}
import org.json4s._
import org.json4s.jackson.JsonMethods._
import scala.reflect.io.File


object Configuration {

  // JSON parser setup, brings in default date formats etc.
  implicit val formats = DefaultFormats

  private[this] val confConnPath      = "iothub-react.connection."
  private[this] val confStreamingPath = "iothub-react.streaming."

  private[this] val conf: Config = ConfigFactory.load()

  // Read-only settings
  val iotHubNamespace : String = conf.getString(confConnPath + "namespace")
  val iotHubName      : String = conf.getString(confConnPath + "name")
  val iotHubPartitions: Int    = conf.getInt(confConnPath + "partitions")
  val accessPolicy    : String = conf.getString(confConnPath + "accessPolicy")
  val accessKey       : String = conf.getString(confConnPath + "accessKey")

  // Tests can override these
  var receiverConsumerGroup: String = EventHubClient.DEFAULT_CONSUMER_GROUP_NAME
  var receiverTimeout      : Long   = conf.getDuration(confStreamingPath + "receiverTimeout").toMillis
  var receiverBatchSize    : Int    = conf.getInt(confStreamingPath + "receiverBatchSize")

  // Read devices configuration from JSON file
  private[this] lazy val devicesJsonFile                       = conf.getString(confConnPath + "devices")
  private[this] lazy val devicesJson: String                   = File(devicesJsonFile).slurp()
  private[this] lazy val devices    : Array[DeviceCredentials] = parse(devicesJson).extract[Array[DeviceCredentials]]

  def deviceCredentials(id: String): DeviceCredentials = {
    val deviceData: Option[DeviceCredentials] = devices.find(x ? x.deviceId == id)
    if (deviceData == None) {
      throw new RuntimeException(s"Device '${id}' credentials not found")
    }
    deviceData.get
  }

  if (!Files.exists(Paths.get(devicesJsonFile))) {
    throw new RuntimeException("Devices credentials not found")
  }
} 
开发者ID:Azure,项目名称:toketi-iothubreact,代码行数:53,代码来源:Configuration.scala

示例9:

//设置package包名称以及导入依赖的类
package com.kylin.scala.hdfs.init

import org.apache.hadoop.conf.Configuration
import org.apache.hadoop.fs.Path

import scala.reflect.io.File


  val conf: Configuration = new Configuration()
  if (File(userConfDir + PATH_TO_HDFS_SITE_XML).exists &&
    File(userConfDir + PATH_TO_CORE_SITE_XML).exists){
    conf.addResource(new Path(userConfDir + PATH_TO_HDFS_SITE_XML))
    conf.addResource(new Path(userConfDir + PATH_TO_CORE_SITE_XML))
    println("success to load conf file : hdfs-site.xml and core-site.xml")
  }
  else
    println("File not find: hdfs-site.xml or core-site.xml")
} 
开发者ID:jinjuting,项目名称:kylin-scala-1.1.0,代码行数:19,代码来源:InitConf.scala

示例10: Numpy

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

import testbed._

import scala.reflect.io.{File, Path}
import scala.sys.process.{ProcessLogger, Process}

class Numpy[ResultType](val pathToPython: String, numpyImportAlias: String = "np") {

  def isInstalled = {
    val testPythonCmd = Process(s"$pathToPython --version")
    val testNumpyCmd = Process(Seq(pathToPython, "-c",  "'import numpy; print(numpy.version)'"))

    def pythonInstalled = {
      var result = ""
      testPythonCmd ! ProcessLogger(line => result += line)

      result contains "Python"
    }

    def numpyInstalled = {
      var result = ""
      testNumpyCmd ! ProcessLogger(line => result += line)

      !(result contains "Error")
    }

    pythonInstalled && numpyInstalled
  }

  val NOT_INSTALLED_MSG: String = s"No numpy installation found with $pathToPython."

  val PYTHON_SRC_FILE_NAME: String = "src_buffer.py"

  def getResult(numpyExpr: String, bufferName: String, resultReader: String => ResultType) = {
    assert(isInstalled, NOT_INSTALLED_MSG)
    val absolutePathToBuffer = Path(bufferName).toAbsolute.path
    val pythonSrcFile = File(PYTHON_SRC_FILE_NAME)
    val pythonFileWriteExpr =
      s"""import numpy as $numpyImportAlias
         |import csv
         |with open('$absolutePathToBuffer', 'w') as buffer_file:
         |        csv_writer = csv.writer(buffer_file, delimiter=',')
         |        for result_line in $numpyExpr:
         |            result_line = [result_line]
         |            csv_writer.writerow(result_line)
       """.stripMargin

    pythonSrcFile.writeAll(pythonFileWriteExpr)

    Process(Seq(pathToPython, pythonSrcFile.toAbsolute.path))!

    resultReader(bufferName)
  }
} 
开发者ID:bethge,项目名称:sketching-testbed,代码行数:56,代码来源:Numpy.scala


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