本文整理汇总了Scala中java.nio.file.FileSystems类的典型用法代码示例。如果您正苦于以下问题:Scala FileSystems类的具体用法?Scala FileSystems怎么用?Scala FileSystems使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了FileSystems类的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: userPreferencesFileContents
//设置package包名称以及导入依赖的类
package com.github.madoc.create_sbt_project.io
import java.nio.charset.Charset
import java.nio.file.{FileSystem, FileSystems, Files}
import java.util.concurrent.atomic.AtomicReference
import com.github.madoc.create_sbt_project.action.framework.ActionEnvironment
import com.github.madoc.create_sbt_project.io.Write.WriteToAppendable
import scala.io.Source
trait FileSystemSupport extends ActionEnvironment {
def userPreferencesFileContents:Option[String]
def writeToStandardOutput:Write
def writeToErrorOutput:Write
}
object FileSystemSupport {
val default:FileSystemSupport = new Default(FileSystems getDefault)
val main:AtomicReference[FileSystemSupport] = new AtomicReference[FileSystemSupport](default)
class Default(val fs:FileSystem) extends FileSystemSupport {
def userPreferencesFileContents = {
val prefsPath = fs getPath userPreferencesFilePath
if(Files.exists(prefsPath) && Files.isRegularFile(prefsPath) && Files.isReadable(prefsPath)) {
val source = Source.fromInputStream(Files newInputStream prefsPath, "utf-8")
try Some(source mkString) finally source.close()
}
else None
}
val writeToErrorOutput = new WriteToAppendable(systemErr)
val writeToStandardOutput = new WriteToAppendable(systemOut)
def fileExists(path:String) = Files exists (fs getPath path)
def isFileWritable(path:String) = Files isWritable (fs getPath path)
def isDirectory(path:String) = Files isDirectory (fs getPath path)
def mkdirs(path:String) = Files createDirectories (fs getPath path)
def outputToFile[A](contents:A, path:String, charset:Charset)(implicit output:Output[A]) = {
val writer = Files.newBufferedWriter(fs getPath path, charset)
try output(contents)(new WriteToAppendable(writer)) finally writer close
}
protected def systemErr:Appendable = System err
protected def systemOut:Appendable = System out
protected def userHomeDirectory:String = System.getProperty("user.home")
protected def userPreferencesFilePath:String =
if(userHomeDirectory endsWith "/") userHomeDirectory + ".create-sbt-project.json"
else userHomeDirectory + "/.create-sbt-project.json"
}
}
示例2: FileTailSourceSpec
//设置package包名称以及导入依赖的类
package akka.stream.alpakka.file.scaladsl
import java.nio.file.FileSystems
import akka.NotUsed
import akka.actor.ActorSystem
import akka.stream.alpakka.file.scaladsl
import akka.stream.scaladsl.Source
import akka.stream.{ActorMaterializer, Materializer}
import scala.concurrent.duration._
object FileTailSourceSpec {
// small sample of usage, tails the first argument file path
def main(args: Array[String]): Unit = {
if (args.length != 1) throw new IllegalArgumentException("Usage: FileTailSourceTest [path]")
val path: String = args(0)
implicit val system: ActorSystem = ActorSystem()
implicit val materializer: Materializer = ActorMaterializer()
// #simple-lines
val fs = FileSystems.getDefault
val lines: Source[String, NotUsed] = scaladsl.FileTailSource.lines(
path = fs.getPath(path),
maxLineSize = 8192,
pollingInterval = 250.millis
)
lines.runForeach(line => System.out.println(line))
// #simple-lines
}
}
示例3: DirectoryChangesSourceSpec
//设置package包名称以及导入依赖的类
package akka.stream.alpakka.file.scaladsl
import java.nio.file.FileSystems
import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import scala.concurrent.duration._
object DirectoryChangesSourceSpec {
def main(args: Array[String]): Unit = {
if (args.length != 1) throw new IllegalArgumentException("Usage: DirectoryChangesSourceTest [path]")
val path: String = args(0)
implicit val system: ActorSystem = ActorSystem()
implicit val materializer = ActorMaterializer()
// #minimal-sample
val fs = FileSystems.getDefault
val changes = DirectoryChangesSource(fs.getPath(path), pollInterval = 1.second, maxBufferSize = 1000)
changes.runForeach {
case (path, change) => println("Path: " + path + ", Change: " + change)
}
// #minimal-sample
}
}
示例4: FileSystemSupportTest
//设置package包名称以及导入依赖的类
package com.github.madoc.create_sbt_project.io
import java.nio.file.FileSystems
import org.scalatest.{FreeSpec, Matchers}
class FileSystemSupportTest extends FreeSpec with Matchers {
"user home directory returns the system property" in {
val fs = new FileSystemSupport.Default(FileSystems getDefault) {
def exposeUserHomeDirectory = userHomeDirectory
}
fs.exposeUserHomeDirectory should be (System getProperty "user.home")
}
"path of user preferences path is composed correctly even when user home ends in a slash" in {
val fs = new FileSystemSupport.Default(FileSystems getDefault) {
def exposeUserPreferencesFilePath = super.userPreferencesFilePath
override protected def userHomeDirectory = "/home/user/"
}
fs.exposeUserPreferencesFilePath should be ("/home/user/.create-sbt-project.json")
}
}
示例5: StreamingTest
//设置package包名称以及导入依赖的类
import org.scalatest._
class StreamingTest extends FlatSpec with Matchers {
"Hello" should "have tests" in {
import java.nio.ByteBuffer
import java.nio.channels.ReadableByteChannel
import java.nio.file.{FileSystems, Files}
@scala.annotation.tailrec
def countStuff(
buffer: ByteBuffer,
byteChannel: ReadableByteChannel,
oldcount: BigInt
): BigInt = {
val newCount = byteChannel.read(buffer)
if (newCount == -1) {
println("Done reading")
oldcount
} else {
println(s"Read ${newCount + oldcount} bytes!")
buffer.clear()
countStuff(buffer, byteChannel, oldcount + newCount)
}
}
Seq("/i/p/hmrc/attachments/README.md").foreach{(fileWithFullPath: String) =>
val byteChannel =
Files.newByteChannel(FileSystems.getDefault().getPath(fileWithFullPath))
countStuff(ByteBuffer.allocateDirect(1024), byteChannel, 0)
byteChannel.close()
}
}
}
示例6: FileIO
//设置package包名称以及导入依赖的类
package swave.core.io.files
import java.io.File
import java.nio.channels.FileChannel
import java.nio.file.{FileSystems, Files, Path, StandardOpenOption}
import scala.util.control.NonFatal
import com.typesafe.config.Config
import swave.core.impl.util.SettingsCompanion
import swave.core.io.Bytes
import swave.core.macros._
object FileIO extends SpoutFromFiles with DrainToFiles {
lazy val userHomePath: Path = FileSystems.getDefault.getPath(System getProperty "user.home")
def resolveFileSystemPath(pathName: String): Path =
if (pathName.length >= 2 && pathName.charAt(0) == '~' && pathName.charAt(1) == File.separatorChar) {
userHomePath.resolve(pathName substring 2)
} else FileSystems.getDefault.getPath(pathName)
val WriteCreateOptions: Set[StandardOpenOption] = {
import StandardOpenOption._
Set(CREATE, TRUNCATE_EXISTING, WRITE)
}
final case class Settings(defaultFileReadingChunkSize: Int, defaultFileWritingChunkSize: Int) {
requireArg(defaultFileReadingChunkSize > 0, "`defaultFileChunkSize` must be > 0")
requireArg(defaultFileWritingChunkSize >= 0, "`defaultFileWritingChunkSize` must be >= 0")
def withDefaultFileReadingChunkSize(defaultFileReadingChunkSize: Int) =
copy(defaultFileReadingChunkSize = defaultFileReadingChunkSize)
def withDefaultFileWritingChunkSize(defaultFileWritingChunkSize: Int) =
copy(defaultFileWritingChunkSize = defaultFileWritingChunkSize)
}
object Settings extends SettingsCompanion[Settings]("swave.core.file-io") {
def fromSubConfig(c: Config): Settings =
Settings(
defaultFileReadingChunkSize = c getInt "default-file-reading-chunk-size",
defaultFileWritingChunkSize = c getInt "default-file-writing-chunk-size")
}
def writeFile[T: Bytes](fileName: String, data: T): Unit = writeFile(resolveFileSystemPath(fileName), data)
def writeFile[T: Bytes](file: File, data: T): Unit = writeFile(file.toPath, data)
def writeFile[T: Bytes](path: Path, data: T, options: StandardOpenOption*): Unit = {
implicit def decorator(value: T): Bytes.Decorator[T] = Bytes.decorator(value)
Files.write(path, data.toArray, options: _*)
()
}
def readFile[T: Bytes](fileName: String): T = readFile(resolveFileSystemPath(fileName))
def readFile[T: Bytes](file: File): T = readFile(file.toPath)
def readFile[T: Bytes](path: Path): T = implicitly[Bytes[T]].apply(Files.readAllBytes(path))
private[io] def quietClose(channel: FileChannel): Unit =
try channel.close()
catch { case NonFatal(_) ? }
}
示例7: DirectoryTemplateSourceSpec
//设置package包名称以及导入依赖的类
package de.frosner.broccoli.templates
import java.nio.file.{FileSystems, Files, Path}
import de.frosner.broccoli.models.{ParameterInfo, Template}
import org.specs2.mutable.Specification
import scala.io.Source
class DirectoryTemplateSourceSpec extends Specification with TemporaryTemplatesContext {
"Loading templates from a directory" should {
"fail if the passed directory is not directory" in {
val directory = FileSystems.getDefault.getPath("not-a-directory")
Files.exists(directory) must beFalse
new DirectoryTemplateSource(directory.toString).loadTemplates must throwA(
new IllegalStateException(s"Templates directory ${directory.toAbsolutePath} is not a directory"))
}
"parse fully specified templates correctly" in { templatesDirectory: Path =>
val templates =
new DirectoryTemplateSource(templatesDirectory.toString).loadTemplates()
templates must contain(
beEqualTo(Template(
"curl",
Source.fromFile(templatesDirectory.resolve("curl/template.json").toFile).mkString,
"A periodic job that sends an HTTP GET request to a specified address every minute.",
Map("URL" -> ParameterInfo("URL", None, Some("localhost:8000"), None),
"enabled" -> ParameterInfo("enabled", None, Some("true"), None))
))).exactly(1)
}
"use a default template description if not provided" in { templatesDirectory: Path =>
val templates =
new DirectoryTemplateSource(templatesDirectory.toString).loadTemplates()
templates.map(_.description) must contain(beEqualTo("curl-without-decription template")).exactly(1)
}
"use default parameters if meta file is not provided" in { templatesDirectory: Path =>
val templates =
new DirectoryTemplateSource(templatesDirectory.toString).loadTemplates()
templates.map(_.parameterInfos) must contain(empty).exactly(1)
}
"not contain templates that failed to parse" in { templatesDirectory: Path =>
val templates =
new DirectoryTemplateSource(templatesDirectory.toString).loadTemplates()
templates.map(_.id) must not contain beEqualTo("broken-template")
}
}
}
示例8: Configuration
//设置package包名称以及导入依赖的类
package net.aruneko.redmineforspigot
import java.nio.file.{Files, FileSystems}
import org.bukkit.command.CommandSender
import org.bukkit.plugin.java.JavaPlugin
import scala.util.control.Exception._
class Configuration(p: JavaPlugin) {
// ?????????????????????????????
if (!p.getDataFolder.exists()) {
p.getDataFolder.mkdirs()
}
// ???????????????
val configFileName = "config.yml"
val configFilePath = FileSystems.getDefault.getPath(p.getDataFolder.toString, configFileName)
// ?????????????????????????
if (!Files.exists(configFilePath)) {
p.getLogger.info("config.yml is not found, creating.")
p.saveDefaultConfig()
} else {
p.getLogger.info("config.yml is found, loading.")
}
// ???????????
val conf = p.getConfig
// RedmineURL???
val url = conf.getString("url")
def getApiKey(sender: CommandSender): MyEither[String, String] = {
val apiKey = catching(classOf[NullPointerException]) opt conf.getString("apiKeys." + sender.getName)
apiKey match {
case None =>
Left("NOTE: You don't set API Key.")
case Some(key) =>
Right(key)
}
}
def setApiKey(sender: CommandSender, apiKey: String): Boolean = {
if (apiKey.matches("[a-f0-9]{40}")) {
conf.set("apiKeys." + sender.getName, apiKey)
p.saveConfig
sender.sendMessage("Saved configuration file.")
} else {
sender.sendMessage("Incorrect API Key format.")
}
true
}
}
示例9: TestData
//设置package包名称以及导入依赖的类
package hyponome.test
import java.nio.file.{FileSystem, FileSystems, Path}
import hyponome._
trait Data {
private val fs: FileSystem = FileSystems.getDefault
val testPDF: Path = fs.getPath(getClass.getResource("/test.pdf").getPath)
val testPDFHash: FileHash = FileHash.fromHex("eba205fb9114750b2ce83db62f9c2a15dd068bcba31a2de32d8df7f7c8d85441")
val testPDFName: Option[String] = Some(testPDF.toFile.getName)
val testPDFContentType: Option[String] = Some("application/octet-stream")
val testPDFLength: Long = testPDF.toFile.length
val testUser: User = User("Alice", "[email protected]")
val testMetadata: Option[Metadata] = Some(Metadata("This is some metadata"))
val testMessageAdd: Option[Message] = Some(Message("I'm adding this file"))
val testMessageRemove: Option[Message] = Some(Message("I'm removing this file"))
case class TestData(file: Path,
hash: FileHash,
name: Option[String],
contentType: Option[String],
length: Long,
metadata: Option[Metadata],
user: User,
message: Option[Message])
val testData = TestData(testPDF, testPDFHash, testPDFName, testPDFContentType, testPDFLength, testMetadata, testUser, testMessageAdd)
val testFile = File(testPDFHash, testPDFName, testPDFContentType, testPDFLength, testMetadata)
}
示例10: BlueprintExample
//设置package包名称以及导入依赖的类
package code
import java.nio.file.FileSystems
import akka.NotUsed
import akka.stream.IOResult
import akka.stream.scaladsl.{FileIO, Flow, Framing, Keep, RunnableGraph}
import akka.util.ByteString
import scala.concurrent.Future
object BlueprintExample extends AkkaStreamsApp {
val file = this.getClass.getClassLoader.getResource("current_inventory.csv")
val inPath = FileSystems.getDefault.getPath(file.getPath)
val outPath = FileSystems.getDefault.getPath("no_inventory.csv")
val fileSource = FileIO.fromPath(inPath)
val fileSink = FileIO.toPath(outPath)
val csvHandler: Flow[String, List[String], NotUsed] =
Flow[String]
.drop(1)
.map(_.split(",").toList)
.log("csvHandler")
val lowInventoryFlow: RunnableGraph[Future[IOResult]] =
fileSource
.via(Framing.delimiter(ByteString("\n"), Integer.MAX_VALUE))
.map(_.utf8String)
.log("Before CSV Handler")
.via(csvHandler)
.filter(list => list(2).toInt == 0)
.log("After filter")
.map { list =>
ByteString(list.mkString(",")) ++ ByteString("\n")
}.toMat(fileSink)(Keep.right)
override def akkaStreamsExample: Future[_] =
lowInventoryFlow.run()
runExample
}