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


Scala Path类代码示例

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


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

示例1: parse

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

import java.io.{InputStream, InputStreamReader}
import java.nio.charset.StandardCharsets
import java.nio.file.{Files, Path, Paths}
import javax.script.ScriptEngineManager

import com.google.common.base.Charsets
import com.google.common.io.CharStreams
import org.luaj.vm2.{LuaTable, LuaValue}

import scala.collection.breakOut
import scala.io.Source

trait FactorioParser[T] {
  import FactorioParser._

  def parse(path: String): Seq[T] = commonParse(readAll(path))
  def parse(path: Path): Seq[T] = commonParse(readAll(path))
  def parse(is: InputStream): Seq[T] = {
    val str = CharStreams.toString(new InputStreamReader(is, Charsets.UTF_8))
    commonParse(str)
  }

  def transport(table: LuaTable): Option[T]

  private[this] def commonParse(target: String): Seq[T] = {
    val dataLua = Source.fromURL(getClass.getResource("/data.lua")).mkString
    val lua = dataLua + target
    val engine = manager.getEngineByName("luaj")
    engine.eval(lua)
    val array: LuaTable = engine.get("array").asInstanceOf[LuaTable]
    tableToSeq(array)(_.checktable()).flatMap(transport)
  }
}

object FactorioParser {
  private val manager = new ScriptEngineManager()

  def readAll(path: String): String = readAll(Paths.get(path))

  def readAll(path: Path): String =
    new String(Files.readAllBytes(path), StandardCharsets.UTF_8)

  def tableToSeq[T](table: LuaTable)(f: LuaValue => T): Seq[T] = {
    table.keys().map(table.get).map(f)(breakOut)
  }

  def tableToMap[K, V](table: LuaTable)(f: LuaValue => K)(g: LuaValue => V): Map[K, V] = {
    table.keys().map { key =>
      f(key) -> g(table.get(key))
    }(breakOut)
  }


} 
开发者ID:ponkotuy,项目名称:FactorioRecipe,代码行数:57,代码来源:FactorioParser.scala

示例2: StorageLocation

//设置package包名称以及导入依赖的类
package hu.blackbelt.cd.bintray.deploy

import java.io.InputStream
import java.nio.file.Path

import com.typesafe.scalalogging.LazyLogging

case class StorageLocation(bucket: String, key: String) {
  override def toString = s"s3://$bucket/$key"
}

case class Project(location: StorageLocation, name: String, version: String)

class Deploy(project: Project) extends LazyLogging {

  logger.info("collecting access properties")
  Access.collect
  logger.info("access info in possession")


  def fetch = S3Get.get(project.location.bucket, project.location.key) _

  private def selectArt(art: Art)(selector: Art => Path) = {
    val subject = selector(art)
    val key = s"${art.groupId.replace('.', '/')}/${art.artifactId}/${art.version}/${subject.getFileName}"
    (key, subject)
  }

  def upload(archive: InputStream, batchSize: Int = 30) = {
    val artifacts = TarGzExtract.getArtifacts(archive)
    val batches = artifacts.sliding(batchSize, batchSize).map(arts => {
      val mapped = arts.flatMap { art =>
        val select = selectArt(art) _
        List(select(_.artifact), select(_.pomFile))
      }
      Batch(mapped)
    }

    ).toList

    val b = new Btray
    val ver = b.version("releases", project.name, project.version)

    ver.map(
      b.uploadTo(_, batches)
    )
  }
} 
开发者ID:tsechov,项目名称:s3-bintray-deploy,代码行数:49,代码来源:Deploy.scala

示例3: Chunkifier

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

import java.io.File
import java.nio.file.{Path, Files}
import scala.math.ceil



object Chunkifier {

  def apply(implicit chunkSize: Int, file: File): List[Chunk] = {
    val src: Array[Byte] = Files.readAllBytes(file.toPath)
    val chunks = for (i <- 0 until chunksCount(file, chunkSize))
      yield Chunk(i, trySlice(src, i * chunkSize, (i + 1) * chunkSize))
    chunks.toList
  }

  def chunksCount(file: File, chunkSize: Int): Int = ceil(file.length.toDouble / chunkSize).toInt

  private def trySlice(implicit src: Array[Byte], from: Int, to: Int) = {
    try {
      src.slice(from, to)
    }
    catch {
      case e: Exception =>
        src.slice(from, src.length)
    }
  }
} 
开发者ID:mprzewie,项目名称:cloudia-utils,代码行数:30,代码来源:Chunk.scala

示例4: SymbolReaderContext

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

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

import io.github.nawforce.apexlink.utils.LinkerLog

import scala.collection.mutable

class SymbolReaderContext(val baseDir: Path, verbose: Boolean) {

  private val _labels = mutable.HashMap[String, Label]()
  private val _customObjects = mutable.HashMap[String, CustomObject]()
  private val _pages = mutable.HashMap[String, Page]()
  private val _apexClasses = mutable.HashMap[String, ApexClass]()

  require(Files.isDirectory(baseDir), "Expecting to see a directory at '" + baseDir.toString + "'")

  def getBaseDir: Path = baseDir

  def isVerbose: Boolean = verbose

  def getClasses: Map[String, ApexClass] = _apexClasses.toMap

  def getLabels: Map[String, Label] = _labels.toMap

  def addLabel(label: Label): Unit = {
    if (_labels.get(label.fullName).isDefined)
      LinkerLog.logMessage(label.location, "Duplicate label found for '" + label.fullName + "'")
    else
      _labels.put(label.fullName, label)
  }

  def addCustomObject(customObject: CustomObject): Unit = {
    if (_customObjects.get(customObject.fullName).isDefined)
      LinkerLog.logMessage(customObject.location, "Duplicate custom object found for '" + customObject.fullName + "'")
    else
      _customObjects.put(customObject.fullName, customObject)
  }

  def addPage(page: Page): Unit = {
    if (_pages.get(page.fullName).isDefined)
      LinkerLog.logMessage(page.location, "Duplicate page found for '" + page.fullName + "'")
    else
      _pages.put(page.fullName, page)
  }

  def addApexClass(apexClass: ApexClass): Unit = {
    if (_apexClasses.get(apexClass.fullName).isDefined)
      LinkerLog.logMessage(apexClass.location, "Duplicate class found for '" + apexClass.fullName + "'")
    else
      _apexClasses.put(apexClass.fullName, apexClass)
  }

  def report(): Unit = {
    System.out.println("Labels loaded: " + _labels.size)
    System.out.println("CustomObjects loaded: " + _customObjects.size)
    System.out.println("Pages loaded: " + _pages.size)
    System.out.println("Classes loaded: " + _apexClasses.size)
  }
} 
开发者ID:nawforce,项目名称:ApexLink,代码行数:61,代码来源:SymbolReaderContext.scala

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

示例6: SymbolReader

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

import java.nio.file.Path

import io.github.nawforce.apexlink.utils.CSTException

class SymbolReader {
  def loadSymbols(ctx: SymbolReaderContext): Unit = {
    throw new CSTException
  }

  def isIgnoreable(path: Path): Boolean = {
    // Ignore stupid OSX files & rogue package.xml files that sometime hangs about
    val fileName = path.getFileName.toString
    fileName == ".DS_Store" || fileName == "package.xml"
  }

} 
开发者ID:nawforce,项目名称:ApexLink,代码行数:19,代码来源:SymbolReader.scala

示例7: LinkContext

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

import java.nio.file.Path

import io.github.nawforce.apexlink.diff.FileChanger
import io.github.nawforce.apexlink.metadata.{ApexClassReader, CustomObjectReader, LabelReader, SymbolReaderContext}
import io.github.nawforce.apexlink.transforms.{BangComments, MakeIsTest, SortLabels}
import io.github.nawforce.apexlink.transforms.experimental.{AssertDelete, LS_QueryLoops}

import scala.collection.JavaConversions._

 class LinkContext private (path: Path, verbose: Boolean) {

  val ctx = new SymbolReaderContext(path, verbose)
  new LabelReader().loadSymbols(ctx)
  new CustomObjectReader().loadSymbols(ctx)
  // TODO: Re-enable page reading with HTML parser
  //new PageReader().loadSymbols(ctx)
  new ApexClassReader().loadSymbols(ctx)

  def report() = ctx.report()

  def transform(transforms : java.util.List[String]) : Unit = {
    val fileChanger: FileChanger = new FileChanger()
    transforms.foreach(transform => {
      println("Running transform " + transform)
      transform match {
        case "sort-labels" => new SortLabels().exec(ctx, fileChanger)
        case "make-istest" => new MakeIsTest().exec(ctx, fileChanger)
        case "bang-comments" => new BangComments().exec(ctx, fileChanger)
        case "exp.assert-delete" => new AssertDelete().exec(ctx, fileChanger)
        case "exp.ls-query-loops" => new LS_QueryLoops().exec(ctx, fileChanger)
        case _ =>
          println("There is no transform " + transform)
      }
    })
    fileChanger.diff()
  }
}

object LinkContext {

  def create(path: Path, verbose: Boolean) : LinkContext = {
    new LinkContext(path, verbose)
  }
} 
开发者ID:nawforce,项目名称:ApexLink,代码行数:47,代码来源:LinkContext.scala

示例8: ConcreteFilesystem

//设置package包名称以及导入依赖的类
package eu.tznvy.jancy.transpiler.helpers

import java.io.InputStream
import java.nio.file.{Files, Path}

import scala.collection.JavaConverters._
import scala.util.Try


class ConcreteFilesystem extends Filesystem {
  override def createDirectories(path: Path): Unit =
    Files.createDirectories(path)

  override def writeFile(path: Path, content: String): Unit = {
    Files.createDirectories(path.getParent)
    Files.write(path, content.getBytes)
  }

  override def readFile(path: Path): Option[String] =
    Try { Files.readAllLines(path) }
      .map(_.asScala.mkString("\n"))
      .toOption

  override def testPath(path: Path): Boolean =
    Files.exists(path)

  override def copy(from: InputStream, to: Path): Unit =
    Files.copy(from, to)
} 
开发者ID:brthanmathwoag,项目名称:jancy,代码行数:30,代码来源:ConcreteFilesystem.scala

示例9: ShellCheckResult

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

import java.nio.file.Path

import codacy.dockerApi._
import codacy.dockerApi.utils.{CommandRunner, FileHelper, ToolHelper}
import play.api.libs.json._

import scala.util.Try

case class ShellCheckResult(file: String, line: Int, column: Int, level: String, code: Int, message: String)

object ShellCheckResult {
  implicit val shellCheckResult = Json.format[ShellCheckResult]
}

object ShellCheck extends Tool {

  override def apply(path: Path, conf: Option[List[PatternDef]], files: Option[Set[Path]])
                    (implicit spec: Spec): Try[List[Result]] = {
    Try {
      val filesToLint: Seq[String] = files.fold {
        FileHelper.listAllFiles(path)
          .map(_.getAbsolutePath).filter(_.endsWith(".sh"))
      } {
        paths =>
          paths.map(_.toString).toList
      }

      val command = List(".cabal/bin/shellcheck", "-f", "json") ++ filesToLint
      CommandRunner.exec(command) match {
        case Right(resultFromTool) =>
          parseToolResult(resultFromTool.stdout, path, conf)
        case Left(failure) =>
          throw failure
      }
    }
  }

  private def parseToolResult(resultFromTool: List[String], path: Path, conf: Option[List[PatternDef]])
                             (implicit spec: Spec): List[Result] = {
    val results = Try(Json.parse(resultFromTool.mkString)).toOption
      .flatMap(_.asOpt[List[ShellCheckResult]]).getOrElse(List.empty)
      .map { result =>
        Issue(
          SourcePath(FileHelper.stripPath(result.file, path.toString)),
          ResultMessage(result.message),
          PatternId(s"SC${result.code}"),
          ResultLine(result.line))
      }

    ToolHelper.getPatternsToLint(conf).fold {
      results
    } { patterns =>
      results.filter { r => patterns.map(_.patternId).contains(r.patternId) }
    }
  }

} 
开发者ID:mrfyda,项目名称:codacy-shellcheck,代码行数:60,代码来源:ShellCheck.scala

示例10: AudioFile

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

import java.nio.file.Path
import javax.sound.sampled.AudioSystem

import org.tritonus.share.sampled.file.TAudioFileFormat
import kokellab.utils.core.bytesToHash

case class AudioFile(bytes: Array[Byte], sha1: Array[Byte], nSeconds: Double)

object AudioFile {

	def read(file: Path): AudioFile = {
		val bytes = audioFileBytes(file)
		AudioFile(bytes, bytesToHash(bytes), audioFileNSeconds(file))
	}

	private def audioFileBytes(file: Path): Array[Byte] = {
		val is = AudioSystem.getAudioInputStream(file.toFile)
		try {
			(Stream.continually(is.read) takeWhile (_ != -1) map (_.toByte)).toArray
		} finally is.close()
	}

	private def audioFileNSeconds(file: Path): Double = {
		val properties = AudioSystem.getAudioFileFormat(file.toFile).asInstanceOf[TAudioFileFormat].properties
		val microseconds = properties.get("duration").asInstanceOf[Long]
		microseconds.toDouble * 1e-6
	}

} 
开发者ID:kokellab,项目名称:kl-common-scala,代码行数:32,代码来源:AudioFile.scala

示例11: PeerId

//设置package包名称以及导入依赖的类
package com.spooky.bittorrent.model

import com.spooky.bittorrent.metainfo.Torrent
import java.nio.ByteBuffer
import java.nio.file.Path
import java.util.BitSet
import com.spooky.bittorrent.Binary
import java.nio.charset.Charset
import scala.annotation.tailrec
import com.spooky.bittorrent.Checksum
import com.spooky.bittorrent.InfoHash

case class PeerId(id: String)
object PeerId {
  val UTF8 = Charset.forName("UTF8")
  def parse(buffer: ByteBuffer): PeerId = {
    val buff = Array.ofDim[Byte](20)
    buffer.get(buff)
    //    val charset = Charset.forName("ASCII")
    PeerId(new String(buff, UTF8).intern())
  }
  def create = PeerId("SPOOKY6-c2b4f6c4h4d9")
}
case class TorrentFileState(have: BitSet) {
  //This is bugged since last piece is generaly not fully utalized
  def getDownloaded(torrent: Torrent): Long = {
      @tailrec
      def rec(bitset: BitSet, index: Int, accumulated: Long, length: Long): Long = {
        if (bitset.size == index) {
          accumulated
        } else rec(bitset, index + 1, if (bitset.get(index)) accumulated + length else accumulated, length)
      }
    rec(have, 0, 0l, torrent.info.pieceLength)
  }
  override def toString: String = {
    "|" + Binary.toBinary(have) + "|"
  }
}
case class TorrentSetup(torrent: Torrent, root: Path)
case class EnrichedTorrentSetup(torrent: Torrent, root: Path, state: TorrentFileState)
case class TorrentStatistics(infoHash: InfoHash, uploaded: Long, downloaded: Long, left: Long, corrupt: Long)
case class TorrentConfiguration(port: Short, numwant: Int)
abstract class AbstractPeer(ip: String, port: Short)
case class Peer(ip: String, port: Short) extends AbstractPeer(ip, port)

//rename to something maybe **Context
case class TorrentRef(info: InfoHash, peerId: PeerId)
object TorrentRef {
  def apply(torrent: Torrent, peerId: PeerId): TorrentRef = TorrentRef(torrent.infoHash, peerId)
} 
开发者ID:zpooky,项目名称:bittorrent,代码行数:51,代码来源:model.scala

示例12: TorrentFileCreator

//设置package包名称以及导入依赖的类
package com.spooky.bittorrent.torrent

import com.spooky.bittorrent.metainfo.Info
import java.nio.file.Path
import com.spooky.bittorrent.metainfo.TorrentFile
import com.spooky.bittorrent.Checksum
import java.nio.ByteBuffer

class TorrentFileCreator {
  def info(files: List[Path], pieceLength: Int, privateTorrent: Boolean, merkleTree: Boolean): Info = {
    val tFiles = torrentFiles(files)
    val cs = checksums(files, Nil, ByteBuffer.allocateDirect(1024 * 4))
    val l = length(files)

    Info(pieceLength = pieceLength, length = l, files = tFiles.map(_._2), pieces = cs, priv = privateTorrent, rootHash = None)
  }

  private def length(files: List[Path]): Long = files match {
    case Nil       => 0
    case (x :: xs) => x.toFile.length + length(xs)
  }

  private def checksums(files: List[Path], result: List[Checksum], read: ByteBuffer): List[Checksum] = files match {
    case Nil       => result
    case (x :: xs) => Nil
  }

  private def torrentFiles(files: List[Path]): List[Tuple2[Path, TorrentFile]] = {
    ???
  }
} 
开发者ID:zpooky,项目名称:bittorrent,代码行数:32,代码来源:TorrentFileCreator.scala

示例13: Config

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

import java.io.File
import java.nio.file.{Path, Paths}

import com.typesafe.config.{Config => TypeSafeConfig, ConfigFactory}
import net.ceedubs.ficus.Ficus._


object Config {
  final private[this] var config: TypeSafeConfig = ConfigFactory.load()

  def set(configFile: File): Unit = {
    config = ConfigFactory.load(ConfigFactory.parseFile(configFile))
  }

  private val defaultPath: String = "src/main/resources"

  final lazy val resourcesDir: String = {
    val path: String = config.as[Option[String]]("resourcesDir").getOrElse(defaultPath)
    val dir: File = new File(path)
    if (dir.canRead && dir.isDirectory) {
      dir.toString
    } else {
      defaultPath
    }
  }

  def resourceFile(filename: String*): Path = {
    val file: File = Paths.get(resourcesDir, filename: _*).toAbsolutePath.toFile
    if (file.canRead && file.isFile) {
      file.toPath
    } else {
      Paths.get(defaultPath, filename: _*).toAbsolutePath
    }
  }

  final lazy val nGram: Int = config.as[Option[Int]]("concept.nGram.n") match {
    case Some(n) if 1 <= n =>
      n
    case _ =>
      1
  }

  final lazy val nGramGap: Int = config.as[Option[Int]]("concept.nGram.gap") match {
    case Some(gap) if 0 <= gap =>
      gap
    case Some(gap) if gap < 0 =>
      Int.MaxValue
    case _ =>
      0
  }

  final lazy val tokenizer: String = config.as[Option[String]]("concept.tokenizer").getOrElse("CharacterNGram")
} 
开发者ID:ynupc,项目名称:scalastringcourseday7,代码行数:56,代码来源:Config.scala

示例14: FileHelper

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

import java.io.File
import java.nio.charset.StandardCharsets
import java.nio.file.{Files, Path, Paths, StandardOpenOption}

object FileHelper {

  def createTmpFile(content: String, prefix: String = "config", suffix: String = ".conf"): Path = {
    Files.write(
      Files.createTempFile(prefix, suffix),
      content.getBytes(StandardCharsets.UTF_8),
      StandardOpenOption.CREATE
    )
  }

  def stripPath(filename: Path, prefix: Path): String = {
    stripPath(filename.toString, prefix.toString)
  }

  def stripPath(filename: String, prefix: String): String = {
    filename.stripPrefix(prefix)
      .stripPrefix("/")
  }

  def listAllFiles(path: String): List[File] = {
    listAllFiles(Paths.get(path))
  }

  def listAllFiles(path: Path): List[File] = {
    recursiveListFiles(path.toFile)
  }

  private def recursiveListFiles(file: File): List[File] = {
    val these = file.listFiles
    (these ++ these.filter(_.isDirectory).flatMap(recursiveListFiles)).toList
  }

} 
开发者ID:codacy,项目名称:codacy-duplication-scala-seed,代码行数:40,代码来源:FileHelper.scala

示例15: ArchivedFileSystem

//设置package包名称以及导入依赖的类
package fr.cnrs.liris.accio.framework.filesystem.archive

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

import fr.cnrs.liris.accio.framework.filesystem.FileSystem
import fr.cnrs.liris.common.util.FileUtils

abstract class ArchivedFileSystem(writeFormat: ArchiveFormat) extends FileSystem {
  override final def read(filename: String, dst: Path): Unit = {
    detectArchive(filename) match {
      case None => doRead(filename, dst)
      case Some(format) =>
        val tmpDir = Files.createTempDirectory(getClass.getSimpleName + "-")
        val tmpArchive = tmpDir.resolve(s"archive.$format")
        doRead(filename, tmpArchive)
        val decompressor = ArchiveFormat.available.find(_.extensions.contains(format)).get
        decompressor.decompress(tmpArchive, dst)
        FileUtils.safeDelete(tmpDir)
    }
  }

  override final def write(src: Path, filename: String): String = {
    val tmpFile = Files.createTempFile(getClass.getSimpleName + "-", writeFormat.extensions.head)
    writeFormat.compress(src, tmpFile)
    doWrite(tmpFile, filename)
  }

  protected def doRead(filename: String, dst: Path): Unit

  protected def doWrite(src: Path, filename: String): String

  private def detectArchive(filename: String) = {
    val archiveExtensions = ArchiveFormat.available.flatMap { format =>
      format.extensions.flatMap { ext =>
        if (filename.endsWith(ext)) {
          Some(ext)
        } else {
          None
        }
      }
    }
    if (archiveExtensions.nonEmpty) {
      Some(archiveExtensions.maxBy(_.length))
    } else {
      None
    }
  }
} 
开发者ID:privamov,项目名称:accio,代码行数:49,代码来源:ArchivedFileSystem.scala


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