本文整理汇总了Scala中java.io.File类的典型用法代码示例。如果您正苦于以下问题:Scala File类的具体用法?Scala File怎么用?Scala File使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了File类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: ApplicationSpec
//设置package包名称以及导入依赖的类
import org.specs2.mutable._
import org.specs2.runner._
import org.junit.runner._
import play.api.test._
import play.api.test.Helpers._
import java.io.File
class ApplicationSpec extends Specification {
val modulePath = new File("./modules/web/")
"Web Module" should {
"send 404 on a bad request" in {
running(FakeApplication(path = modulePath)) {
route(FakeRequest(GET, "/boum")) must beSome.which(status(_) == NOT_FOUND)
}
}
"render the index page" in {
running(FakeApplication(path = modulePath)) {
val index = route(FakeRequest(GET, "/")).get
status(index) must equalTo(OK)
contentType(index) must beSome.which(_ == "text/html")
contentAsString(index) must contain("WEB template")
}
}
}
}
示例2: NodeTest
//设置package包名称以及导入依赖的类
package communication
import java.io.File
import akka.actor.{ActorRef, ActorSystem}
import akka.testkit.{ImplicitSender, TestKit}
import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike}
import index.{DirectoryIndex, FileIndex}
class NodeTest() extends TestKit(ActorSystem("NodeTest")) with ImplicitSender
with WordSpecLike with Matchers with BeforeAndAfterAll {
implicit val homeDirPath = "/home/mike/Programming/scala/Cloudia"
override def afterAll {
TestKit.shutdownActorSystem(system)
}
"Node" must {
"send back directory index if pinged" in {
val node: ActorRef = system.actorOf(Node.props(homeDirPath))
node ! Ping()
expectMsgPF() {
case DirectoryIndex(_) => ()
}
}
}
it must {
"send back file manifest if one was requested" in {
val node: ActorRef = system.actorOf(Node.props(homeDirPath))
val fileIndex = new FileIndex(new File("src/test/resources/chunkifierTest"))
node ! Request(fileIndex)
expectMsgPF() {
case FileManifest(_, _) => ()
}
}
}
}
示例3: EmberRunner
//设置package包名称以及导入依赖的类
import java.io.File
import java.net.InetSocketAddress
import play.sbt.PlayRunHook
import sbt._
object EmberRunner {
def apply(logger: Logger,
baseDir: File,
port: Int = 4200): PlayRunHook = {
object EmberRunHook extends PlayRunHook {
var watchProcess: Option[Process] = None
override def beforeStarted(): Unit = {
if (baseDir.exists()) {
logger.info("Executing npm install")
val npm = Process(Seq("npm", "install"), baseDir).lines
npm.foreach(logger.info(_))
logger.info("Executing bower install")
val bower = Process(Seq("bower", "install"), baseDir).lines
bower.foreach(logger.info(_))
} else {
logger.info(s"Skipping npm and bower install. UI application directory ${baseDir.getAbsolutePath} not found.")
}
}
override def afterStarted(addr: InetSocketAddress): Unit = {
addr.getAddress.getHostAddress
val url = s"http://localhost:${addr.getPort}"
if (baseDir.exists()) {
logger.info(s"Starting ember server in development mode. Setting proxy to $url")
watchProcess = Some(Process(Seq("ember", "serve", "--proxy", url, "--port", port.toString), baseDir).run(logger))
} else {
logger.info(s"Skipping ember server start. UI application directory ${baseDir.getAbsolutePath} not found.")
}
}
override def afterStopped(): Unit = {
logger.info("Attempting to stop ember server")
watchProcess.foreach(_.destroy())
watchProcess = None
}
}
EmberRunHook
}
}
示例4: fileAndLine
//设置package包名称以及导入依赖的类
import java.io.File
import scala.io.Source
val dir = args(0)
def fileAndLine = for (
file <- new File(dir).listFiles if file.isFile && file.canRead;
line <- Source.fromFile(file).getLines.toList
) yield (file, line)
val longestLine = fileAndLine
.reduceLeft(
(l, r) =>
if (getPrefix(l._1, l._2).length > getPrefix(r._1, r._2).length) l else r
)
val longestPrefix = getPrefix(longestLine._1, longestLine._2).length
fileAndLine.foreach(f => println(padString(getPrefix(f._1, f._2), longestPrefix) + " " + f._2))
def padString(string: String, max: Int, char: Char = ' ') = char.toString * (max - string.length) + string
def getPrefix(file: File, line: String) = file.getName + ":" + line.length
示例5: 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())
}
}
示例6: HBaseRestServer
//设置package包名称以及导入依赖的类
package com.hadooparchitecturebook.taxi360.server.hbase
import java.io.File
import com.sun.jersey.spi.container.servlet.ServletContainer
import org.apache.hadoop.hbase.HBaseConfiguration
import org.mortbay.jetty.Server
import org.mortbay.jetty.servlet.{Context, ServletHolder}
object HBaseRestServer {
def main(args:Array[String]): Unit = {
if (args.length == 0) {
println("<port> <configDir> <numberOfSalts> <customerTableName>")
}
val port = args(0).toInt
val hbaseConfigFolder = args(1)
val numberOfSalts = args(2).toInt
val appEventTableName = args(3)
val conf = HBaseConfiguration.create()
conf.addResource(new File(hbaseConfigFolder + "hbase-site.xml").toURI.toURL)
HBaseGlobalValues.init(conf, numberOfSalts,
appEventTableName)
val server = new Server(port)
val sh = new ServletHolder(classOf[ServletContainer])
sh.setInitParameter("com.sun.jersey.config.property.resourceConfigClass", "com.sun.jersey.api.core.PackagesResourceConfig")
sh.setInitParameter("com.sun.jersey.config.property.packages", "com.hadooparchitecturebook.taxi360.server.hbase")
sh.setInitParameter("com.sun.jersey.api.json.POJOMappingFeature", "true")
val context = new Context(server, "/", Context.SESSIONS)
context.addServlet(sh, "/*")
println("starting HBase Rest Server")
server.start()
println("started HBase Rest Sserver")
server.join()
}
}
示例7: 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)
}
}
}
示例8: ChunkifyAndBuildTest
//设置package包名称以及导入依赖的类
package io
import java.io.File
import communication.FileManifest
import index.FileIndex
import org.scalatest.{FlatSpec, Matchers}
class ChunkifyAndBuildTest extends FlatSpec with Matchers {
implicit val homeDirPath = "/home/mike/Programming/scala/"
"Chunkifier and FileBuilder" should "chunkify and rebuild file properly" in {
val originalFile = new File("src/test/resources/chunkifierTest")
val chunksList: List[Chunk] = Chunkifier(100, originalFile)
val fileManifest = FileManifest(new FileIndex(originalFile), 100)
val fileBuilder = new FileBuilder(fileManifest)
chunksList.foreach(chunk => fileBuilder.accept(chunk))
fileBuilder.build()
val newChunksList: List[Chunk] = Chunkifier(100, originalFile)
chunksList.indices.foreach { i => chunksList(i).content should equal(newChunksList(i).content) }
}
}
示例9: Files
//设置package包名称以及导入依赖的类
package org.bruchez.olivier.dsstoreremover
import java.io.File
import scala.annotation.tailrec
object Files {
def filesInDirectory(directory: File, recursive: Boolean, includeDirectories: Boolean): Seq[File] = {
val (directories, files) = Option(directory.listFiles()).fold(Seq[File]())(_.toSeq).partition(_.isDirectory)
val subDirectoriesAndFiles =
if (recursive) directories.flatMap(filesInDirectory(_, recursive = true, includeDirectories)) else Seq()
(if (includeDirectories) directories else Seq()) ++ files ++ subDirectoriesAndFiles
}
def isMacOsMetadataFile(file: File): Boolean = {
val filename = file.getName
lazy val isDsStoreFile = filename == MacOsDsStoreFilename
lazy val isMetadataFile = filename.startsWith(MacOsMetadataFilePrefix) && {
val baseFile = new File(file.getParentFile, filename.substring(MacOsMetadataFilePrefix.length))
baseFile.exists()
}
isDsStoreFile || isMetadataFile
}
private val MacOsDsStoreFilename = ".DS_Store"
private val MacOsMetadataFilePrefix = "._"
def nonExistingFile(directory: File, baseFilename: String): File = {
@tailrec
def nonExistingFile(index: Int): File = {
val suffix = if (index <= 0) "" else s".$index"
val fileToTest = new File(directory, baseFilename + suffix)
if (!fileToTest.exists()) fileToTest else nonExistingFile(index + 1)
}
nonExistingFile(index = 0)
}
}
示例10: EulerUtils
//设置package包名称以及导入依赖的类
package org.nason.euler
import java.io.{File, FileWriter}
object EulerUtils
{
val DataRoot = "/home/sorensjm/workspace/euler/data"
val DataRoot2 = "/Users/jon/Documents/IdeaProjects/euler-jms-scala/data"
def writeFile(file: File, content: String) =
if (file.exists() && !file.canWrite())
System.err.println("File " + file + " is not writable")
else {
val writer = new FileWriter(file, false)
writer.write(content)
writer.close()
}
def readDataFile( fileName:String ) : Iterator[String] = {
val file = new File(DataRoot2,fileName)
if (!file.exists()) {
System.err.println("Can not find file %s/%s".format(DataRoot2,fileName))
Array[String]().iterator
} else {
io.Source.fromFile(file).getLines()
}
}
def timing[F]( f: =>F ) =
{
val then = System.nanoTime
val ans = f
val now = System.nanoTime
println( "Took %g sec".format( (now-then).toDouble*1e-9 ) )
ans
}
}
示例11: SnapshotGenerationSpec
//设置package包名称以及导入依赖的类
package com.commodityvectors.snapshotmatchers
import java.io.File
import org.apache.commons.io.FileUtils
import org.scalatest.{BeforeAndAfterEach, Matchers, fixture}
import scala.util.Try
class SnapshotGenerationSpec extends fixture.WordSpec with Matchers with SnapshotMatcher with BeforeAndAfterEach {
val snapshotFolder: String = "scalatest-snapshot-matcher-core/src/test/__snapshots__"
val currentSpecPath: String = s"$snapshotFolder/com/commodityvectors/snapshotmatchers/SnapshotGenerationSpec"
override def afterEach(): Unit = {
Try(FileUtils.deleteDirectory(new File(snapshotFolder)))
}
"SnapshotMatcher" should {
"generate snapshot file with expectation" in { implicit test =>
val value: Int = 1
value should matchSnapshot[Int]()
FileUtils.readFileToString(
new File(s"$currentSpecPath/snapshotmatcher-should-generate-snapshot-file-with-expectation.snap")
) shouldEqual "1"
}
"generate file with custom id" in { implicit test =>
val value = 10
value should matchSnapshot[Int]("customId")
FileUtils.readFileToString(
new File(s"$currentSpecPath/customId.snap")
) shouldEqual "10"
}
}
}
示例12: ImageCensorontroller
//设置package包名称以及导入依赖的类
package controllers
import javax.inject._
import play.api._
import play.api.mvc._
import play.api.data._
import play.api.data.Forms._
@Singleton
class ImageCensorontroller @Inject() extends Controller {
def index(imageId: Long) = Action {
Ok(views.html.index("Your new application is ready."))
}
def save(imageId: Long) = Action(parse.multipartFormData) { request =>
request.body.file("image").map { image =>
import java.io.File
image.ref.moveTo(new File(s"/tmp/faceblock/completed/$imageId"))
Redirect(routes.ImageViewController.index(imageId))
}.getOrElse {
Redirect(routes.ImageCensorController.index).flashing(
"error" -> "Missing file")
}
}
}
示例13: ImageCensorController
//设置package包名称以及导入依赖的类
package controllers
import javax.inject._
import play.api._
import play.api.mvc._
import play.api.data._
import play.api.data.Forms._
@Singleton
class ImageCensorController @Inject() extends Controller {
def index = Action {
Ok(views.html.index("Your new application is ready."))
}
def upload = Action(parse.multipartFormData) { request =>
request.body.file("image").map { image =>
import java.io.File
val filename = image.filename
//Generate some unique id.
val imageId: Long = 1
val contentType = image.contentType
image.ref.moveTo(new File(s"/tmp/faceblock/inprogress/$imageId"))
Redirect(routes.ImageCensorController.index(imageId))
}.getOrElse {
Redirect(routes.ImageUploadController.index).flashing(
"error" -> "Missing file")
}
}
}
示例14: 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))
}
}
示例15: resourceAsStreamFromSrc
//设置package包名称以及导入依赖的类
import java.io.File
package object common {
def resourceAsStreamFromSrc(resourcePath: List[String]): Option[java.io.InputStream] = {
val classesDir = new File(getClass.getResource(".").toURI)
val projectDir = classesDir.getParentFile.getParentFile.getParentFile.getParentFile
val resourceFile = subFile(projectDir, ("src" :: "main" :: "resources" :: resourcePath): _*)
if (resourceFile.exists)
Some(new java.io.FileInputStream(resourceFile))
else
None
}
}