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


Scala BasicFileAttributes类代码示例

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


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

示例1: TraversePath

//设置package包名称以及导入依赖的类
package io.github.nawforce.apexlink.utils

import java.nio.file._
import java.nio.file.attribute.BasicFileAttributes

import scala.collection.Traversable

class TraversePath(path: Path) extends Traversable[(Path, BasicFileAttributes)] {

  // Make foreach receive a function from Tuple2 to Unit
  def foreach[U](f: ((Path, BasicFileAttributes)) => U) {

    class Visitor extends SimpleFileVisitor[Path] {
      var error: Option[Throwable] = None

      override def visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult = try {
        // Pass a tuple to f
        f(file -> attrs)
        FileVisitResult.CONTINUE
      } catch {
        case ex: Throwable =>
          error = Some(ex)
          FileVisitResult.TERMINATE
      }
    }

    val v = new Visitor
    Files.walkFileTree(path, v)
    v.error.exists(ex => throw ex)
  }
} 
开发者ID:nawforce,项目名称:ApexLink,代码行数:32,代码来源:TraversePath.scala

示例2: PageReader

//设置package包名称以及导入依赖的类
package io.github.nawforce.apexlink.metadata

import java.nio.file.attribute.BasicFileAttributes
import java.nio.file.{Files, Path}

import io.github.nawforce.apexlink.utils.{LinkerException, LinkerLog, TraversePath, XMLLineLoader}

class PageReader extends SymbolReader {

  override def loadSymbols(ctx: SymbolReaderContext): Unit = {
    try {
      val pagesDir = ctx.getBaseDir.resolve("pages")
      LinkerLog.ifNotLogAndThrow(Files.isDirectory(pagesDir), 0, "Pages directory is not present")

      val traverse = new TraversePath(pagesDir)
      traverse foreach {
        case (file: Path, attr: BasicFileAttributes) =>
          if (attr.isRegularFile && file.toString.endsWith(".page")) {
            loadPage(ctx, file.getFileName.toString.replaceFirst(".page$", ""), file)
          } else if (attr.isRegularFile && file.toString.endsWith(".page-meta.xml")) {
            // Ignore
          } else if (attr.isRegularFile) {
            if (!isIgnoreable(file))
              LinkerLog.logMessage(file.toString, 0, "Unexpected file in pages directory")
          } else {
            LinkerLog.logMessage(file.toString, 0, "Only expected to find files in pages directory")
          }
      }
    }
    catch {
      case _: LinkerException => () // Ignore, just used to abort processing
    }
  }

  private def loadPage(ctx: SymbolReaderContext, fullName: String, objectFile: Path): Unit = {
    LinkerLog.pushContext(objectFile.toString)
    try {
      val root = XMLLineLoader.loadFile(objectFile.toString)

      Page.create(fullName, root).foreach(o => ctx.addPage(o))
    } finally {
      LinkerLog.popContext()
    }
  }
} 
开发者ID:nawforce,项目名称:ApexLink,代码行数:46,代码来源:PageReader.scala

示例3: CustomObjectReader

//设置package包名称以及导入依赖的类
package io.github.nawforce.apexlink.metadata

import java.nio.file.attribute.BasicFileAttributes
import java.nio.file.{Files, Path}

import io.github.nawforce.apexlink.utils._

class CustomObjectReader extends SymbolReader {

  override def loadSymbols(ctx: SymbolReaderContext): Unit = {
    try {
      val objectsDir = ctx.getBaseDir.resolve("objects")
      if (Files.exists(objectsDir)) {
        LinkerLog.ifNotLogAndThrow(Files.isDirectory(objectsDir), 0, "objects is present but not a directory")

        val traverse = new TraversePath(objectsDir)
        traverse foreach {
          case (file: Path, attr: BasicFileAttributes) =>
            if (attr.isRegularFile && file.toString.endsWith(".object")) {
              loadObject(ctx, file.getFileName.toString.replaceFirst(".object$", ""), file)
            } else if (attr.isRegularFile) {
              if (!isIgnoreable(file))
                LinkerLog.logMessage(file.toString, 0, "Unexpected file in objects directory")
            } else {
              LinkerLog.logMessage(file.toString, 0, "Only expected to find files in objects directory")
            }
        }
      }
    }
    catch {
      case _: LinkerException => () // Ignore, just used to abort processing
    }
  }

  def loadObject(ctx: SymbolReaderContext, fullName: String, objectFile: Path): Unit = {
    LinkerLog.pushContext(objectFile.toString)
    try {
      val root = XMLLineLoader.loadFile(objectFile.toString)
      XMLUtils.ifNotElemLogAndThrow(root, "CustomObject")

      CustomObject.create(fullName, root).foreach(o => ctx.addCustomObject(o))
    } finally {
      LinkerLog.popContext()
    }
  }
} 
开发者ID:nawforce,项目名称:ApexLink,代码行数:47,代码来源:CustomObjectReader.scala

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

示例5: apply

//设置package包名称以及导入依赖的类
package pl.ekodo.json.files

import java.io.IOException
import java.nio.file.attribute.BasicFileAttributes
import java.nio.file.{FileVisitResult, Files, Path, SimpleFileVisitor}

import pl.ekodo.json.model.CaseClass


  def apply(outputDir: Path, classes: Iterable[CaseClass]): Unit = {
    val dir = prepareOutputFolder(outputDir)
    classes.foreach { cc =>
      val s = ScalaTypePrinter(cc)
      Files.write(dir.resolve(s"${cc.name}.scala"), s.getBytes)
    }
  }

  private def prepareOutputFolder(output: Path) = {
    if (Files.exists(output)) {
      Files.walkFileTree(output, new SimpleFileVisitor[Path] {
        override def visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult = {
          Files.delete(file)
          FileVisitResult.CONTINUE
        }

        override def postVisitDirectory(dir: Path, exc: IOException): FileVisitResult = {
          Files.delete(dir)
          FileVisitResult.CONTINUE
        }
      })
    }
    Files.createDirectory(output)
  }

} 
开发者ID:marcindb,项目名称:json-to-case-class,代码行数:36,代码来源:FilesGenerator.scala

示例6: SbtTestRunner

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

import java.nio.charset.StandardCharsets
import java.nio.file._
import java.nio.file.attribute.BasicFileAttributes

import scala.sys.process.{Process, ProcessLogger}
import scala.util.Try

object SbtTestRunner {

  def createProjectAndTest(solution: String, appAbsolutePath: String): String = {
    import scala.collection.JavaConversions._
    Try {
      val buildSbt = List(
        """lazy val root = (project in file("."))""",
        """  .settings(""",
        """    scalaVersion := "2.11.7",""",
        """    libraryDependencies += "org.scalatest" %% "scalatest" % "2.2.6" % "test"""",
        """  )"""
      )
      val d = Files.createTempDirectory("test")
      Files.write(d.resolve("build.sbt"), buildSbt, StandardCharsets.UTF_8)

      val project = d.resolve("project")
      Files.createDirectory(project)

      Files.write(project.resolve("build.properties"), List("sbt.version=0.13.9"), StandardCharsets.UTF_8)

      val solutionTargetPath = d.resolve("src").resolve("main").resolve("scala")
      Files.createDirectories(solutionTargetPath)
      Files.write(solutionTargetPath.resolve("UserSolution.scala"), List("package tests", s"object SleepInSolution {$solution}"), StandardCharsets.UTF_8)

      val testTargetPath = d.resolve("src").resolve("test").resolve("scala")
      Files.createDirectories(testTargetPath)
      val testSourcePath = Paths.get(appAbsolutePath, "test", "tests")

      Files.walkFileTree(testSourcePath, new SimpleFileVisitor[Path] {
        override def visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult = {
          Files.copy(file, testTargetPath.resolve(testSourcePath.relativize(file)))
          FileVisitResult.CONTINUE
        }
      })
      val sbtCommands = Seq("sbt", "-Dsbt.log.noformat=true", "test")
      val output = new StringBuilder
      Process(sbtCommands, d.toFile).!(ProcessLogger(line => output append line append "\n"))
      output.toString()
      //TODO: we need to clean all temp folders
    }.getOrElse("Test failed")
  }
} 
开发者ID:DmytroOrlov,项目名称:devgym,代码行数:52,代码来源:SbtTestRunner.scala

示例7: childrenOf

//设置package包名称以及导入依赖的类
package mco.io.files

import java.nio.file.attribute.BasicFileAttributes

import cats.free.Free
import freasymonad.cats.free

// $COVERAGE-OFF$Macro-generated code
@free sealed trait MonadicIO {
  sealed trait OperationsADT[A]
  type FreeIO[A] = Free[OperationsADT, A]

  def childrenOf(path: Path)                     : FreeIO[Stream[Path]]
  def descendantsOf(path: Path)                  : FreeIO[Stream[Path]]
  def removeFile(path: Path)                     : FreeIO[Unit]
  def isRegularFile(path: Path)                  : FreeIO[Boolean]
  def isDirectory(path: Path)                    : FreeIO[Boolean]
  def archiveEntries(path: Path)                 : FreeIO[Set[String]]
  def extract(path: Path, ft: Map[String, Path]) : FreeIO[Unit]
  def readBytes(path: Path)                      : FreeIO[Array[Byte]]
  def setContent(path: Path, cnt: Array[Byte])   : FreeIO[Unit]
  def createDirectory(path: Path)                : FreeIO[Unit]
  def copyTree(source: Path, dest: Path)         : FreeIO[Unit]
  def moveTree(source: Path, dest: Path)         : FreeIO[Unit]
  def stat(path: Path)                           : FreeIO[BasicFileAttributes]
}
// $COVERAGE-ON 
开发者ID:oleg-py,项目名称:mco,代码行数:28,代码来源:MonadicIO.scala

示例8: withTemporaryFolder

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

import java.io.IOException
import java.nio.file.attribute.BasicFileAttributes
import java.nio.file.{FileVisitResult, Files, Path, SimpleFileVisitor}

import org.scalatest._

import scala.util.Try

trait BaseSpec extends FlatSpec with Logger {

  def withTemporaryFolder[T](f: Path => T): T = {
    val dir = Files.createTempDirectory("goahead")
    logger.debug(s"Created temporary directory $dir")
    try {
      f(dir)
    } finally {
      Try(Files.walkFileTree(dir, BaseSpec.DeleteAllVisitor))
      logger.debug(s"Deleted temporary directory $dir")
    }
  }
}

object BaseSpec {
  object DeleteAllVisitor extends SimpleFileVisitor[Path] {
    override def visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult = {
      Files.delete(file)
      FileVisitResult.CONTINUE
    }

    override def postVisitDirectory(dir: Path, exc: IOException): FileVisitResult = {
      Files.delete(dir)
      FileVisitResult.CONTINUE
    }
  }
} 
开发者ID:cretz,项目名称:goahead,代码行数:38,代码来源:BaseSpec.scala

示例9: Files

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

import java.io.{File, IOException}
import java.nio.file.attribute.BasicFileAttributes
import java.nio.file.{FileVisitResult, FileVisitor, Path, Paths, Files => NioFiles}

import scala.io.Source


object Files {

  def walkFiles(directory: String)(fn: Path => Unit) = {
    NioFiles.walkFileTree(Paths.get(directory), new FileVisitor[Path] {
      def visitFileFailed(file: Path, exc: IOException): FileVisitResult = FileVisitResult.CONTINUE

      def visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult = {
        fn(file);
        FileVisitResult.CONTINUE
      }

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

      def postVisitDirectory(dir: Path, exc: IOException): FileVisitResult = FileVisitResult.CONTINUE
    })
  }

  def printToFile(f: java.io.File)(op: java.io.PrintWriter => Unit) {
    val p = new java.io.PrintWriter(f)
    try {
      op(p)
    } finally {
      p.close()
    }
  }
}

object SetHeaders {
  def updateFile(matcher: Path => Boolean, headerPrefix: String)(newHeader: String)(path: Path) = {
    val file = path.toFile
    if (matcher(path)) {
      val list = Source.fromFile(file).getLines().toList
      val newValue = list match {
        case head :: tail if head.startsWith(headerPrefix) => newHeader :: tail
        case x => newHeader :: x
      }
      Files.printToFile(file)(pw => newValue.foreach(line => pw.write(line + "\r\n")))
    }
  }

  def main(args: Array[String]) {
    val updater = updateFile((path: Path) => path.toFile.getName.endsWith(".scala"), "") _
    Files.walkFiles(".")(path => updater(path))
    updater(Paths.get("."))
  }
} 
开发者ID:phil-rice,项目名称:CddCore2,代码行数:56,代码来源:Files.scala

示例10: foreach

//设置package包名称以及导入依赖的类
package de.frosner.broccoli.util

import java.io.IOException
import java.nio.file.attribute.BasicFileAttributes
import java.nio.file.{FileVisitResult, FileVisitor, Files, Path}

import org.specs2.execute.{AsResult, Result}
import org.specs2.specification.ForEach


trait TemporaryDirectoryContext extends ForEach[Path] {
  override protected def foreach[R: AsResult](f: (Path) => R): Result = {
    val tempDirectory = Files.createTempDirectory(getClass.getName)
    try {
      AsResult(f(tempDirectory))
    } finally {
      Files.walkFileTree(
        tempDirectory,
        new FileVisitor[Path] {
          override def postVisitDirectory(dir: Path, exc: IOException): FileVisitResult = {
            Files.delete(dir)
            FileVisitResult.CONTINUE
          }

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

          override def visitFileFailed(file: Path, exc: IOException): FileVisitResult = throw exc

          override def preVisitDirectory(dir: Path, attrs: BasicFileAttributes): FileVisitResult =
            FileVisitResult.CONTINUE
        }
      )
    }
  }
} 
开发者ID:FRosner,项目名称:cluster-broccoli,代码行数:39,代码来源:TemporaryDirectoryContext.scala

示例11: FilePathManagerTest

//设置package包名称以及导入依赖的类
package com.bwsw.commitlog.filesystem

import java.io.{File, IOException}
import java.nio.file._
import java.nio.file.attribute.BasicFileAttributes

import org.scalatest.{BeforeAndAfterAll, FlatSpec, Matchers}


class FilePathManagerTest extends FlatSpec with Matchers with BeforeAndAfterAll {
  it should "return proper paths" in {
    val fpm = new FilePathManager("target")

    FilePathManager.CATALOGUE_GENERATOR = () => "1111/22/33"
    fpm.getNextPath() shouldBe "target/1111/22/33/0"
    fpm.getNextPath() shouldBe "target/1111/22/33/1"
    fpm.getNextPath() shouldBe "target/1111/22/33/2"

    FilePathManager.CATALOGUE_GENERATOR = () => "1111/22/34"
    fpm.getNextPath() shouldBe "target/1111/22/34/0"
    fpm.getNextPath() shouldBe "target/1111/22/34/1"

    FilePathManager.CATALOGUE_GENERATOR = () => "2222/22/34"
    fpm.getNextPath() shouldBe "target/2222/22/34/0"
    fpm.getNextPath() shouldBe "target/2222/22/34/1"

    new File("target/2222/22/35").mkdirs()
    new File("target/2222/22/35/0.dat").createNewFile()
    new File("target/2222/22/35/1.dat").createNewFile()
    FilePathManager.CATALOGUE_GENERATOR = () => "2222/22/35"
    fpm.getNextPath() shouldBe "target/2222/22/35/2"
  }

  it should "throw an exception if path is not a dir" in {
    val dir = "target/fpm"
    new File(dir).mkdirs()
    new File("target/fpm/0.dat").createNewFile()
    intercept[IllegalArgumentException] {
      val fpm1 = new FilePathManager("target/fpm/0.dat")
    }
    intercept[IllegalArgumentException] {
      val fpm2 = new FilePathManager("")
    }
  }

  override def afterAll = {
    List("target/1111", "target/2222").foreach(dir =>
    Files.walkFileTree(Paths.get(dir), new SimpleFileVisitor[Path]() {
      override def visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult = {
        Files.delete(file)
        FileVisitResult.CONTINUE
      }

      override def postVisitDirectory(dir: Path, exc: IOException): FileVisitResult = {
        Files.delete(dir)
        FileVisitResult.CONTINUE
      }
    }))
  }
} 
开发者ID:bwsw,项目名称:journaled-commit-log,代码行数:61,代码来源:FilePathManagerTest.scala

示例12: SingleTVShowMatch

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

import java.nio.file.attribute.BasicFileAttributes
import java.nio.file._

import com.google.inject.{Singleton, Inject}
import mediainfo.tv.{TVShowSearchResult, TVShowInfo}
import scala.collection.JavaConverters._
import scala.collection.mutable
import scala.concurrent.{ExecutionContext, Future, Await}
import scala.concurrent.duration.Duration

sealed trait TVShowMatch

case class SingleTVShowMatch(searchResult: TVShowSearchResult) extends TVShowMatch
case class MultiplePossibleTVShowMatch(searchResults: Seq[TVShowSearchResult]) extends TVShowMatch

class TVDirectoryFileVisiter(scanDir: Path, tvShowInfo: TVShowInfo)(implicit exec: ExecutionContext) extends SimpleFileVisitor[Path] {
  val showMatches = mutable.Set.empty[TVShowMatch]

  override def preVisitDirectory(directory: Path, attributes: BasicFileAttributes): FileVisitResult = {
    if (directory == scanDir)
      return FileVisitResult.CONTINUE
    val name = directory.getFileName
    val showSearchResultF: Future[Option[TVShowMatch]] = tvShowInfo.showSearch(name.toString).map { results: Seq[TVShowSearchResult] =>
      if (results.size == 1)
        Some(SingleTVShowMatch(searchResult = results.head))
      else if (results.size > 1)
        Some(MultiplePossibleTVShowMatch(searchResults = results))
      else
        None
    }
    Await.result(showSearchResultF, atMost = Duration.Inf) match {
      case Some(result) => showMatches += result; FileVisitResult.SKIP_SUBTREE
      case _ => FileVisitResult.CONTINUE
    }
  }
}

@Singleton
class TVDirectoryScanner @Inject()(tvShowInfo: TVShowInfo)(implicit exec: ExecutionContext) {
  def scanDir(directory: String): Set[TVShowMatch] = {
    val scanDirPath = FileSystems.getDefault.getPath(directory)
    val visiter = new TVDirectoryFileVisiter(scanDirPath, tvShowInfo)
    Files.walkFileTree(
      scanDirPath,
      Set(FileVisitOption.FOLLOW_LINKS).asJava,
      Integer.MAX_VALUE,
      visiter
    )

    Set.empty ++ visiter.showMatches
  }
} 
开发者ID:pequalsnp,项目名称:portroyal,代码行数:55,代码来源:TVDirectoryScanner.scala

示例13: TestUtil

//设置package包名称以及导入依赖的类
package spinoco.fs2.zk

import java.io.IOException
import java.nio.file.attribute.BasicFileAttributes
import java.nio.file.{FileVisitResult, Files, Path, SimpleFileVisitor}

import fs2.util.Async


object TestUtil {

  def removeRecursively[F[_]](path:Path)(implicit F:Async[F]):F[Unit] = {
    F.suspend { F.pure {
      Files.walkFileTree(path, new SimpleFileVisitor[Path] {
        override def visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult = {
          Files.delete(file)
          FileVisitResult.CONTINUE
        }

        override def postVisitDirectory(dir: Path, exc: IOException): FileVisitResult = {
          Files.delete(dir)
          FileVisitResult.CONTINUE
        }
      })
      ()
    }}
  }

} 
开发者ID:Spinoco,项目名称:fs2-zk,代码行数:30,代码来源:TestUtil.scala


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