• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala Files类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: DirectoryIndex

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

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

import util.{NotADirectoryException, NotAFileException}


case class DirectoryIndex(private val directory: File)(private implicit val homeDirPath: String) extends Index(directory) {
  override val handler: File = {
    if (!directory.exists || directory.isFile) throw NotADirectoryException(directory)
    directory
  }
  override val path: String = Paths.get(homeDirPath).relativize(Paths.get(handler.getCanonicalPath)).toString
  val subFiles: List[FileIndex] = handler.listFiles.filter(_.isFile).map(FileIndex(_)(homeDirPath)).toList
  val subDirectories: List[DirectoryIndex] = handler.listFiles.filter(_.isDirectory).map(DirectoryIndex(_)(homeDirPath)).toList

  override def find(fileName: String): List[_ <: Index] = {
    (subFiles ++ subDirectories).map(_.find(fileName)).fold(super.find(fileName))(_ ++ _)
  }
}

object DirectoryIndex {
  def apply(directoryName: String)(implicit homeDirPath: String): DirectoryIndex = {
    DirectoryIndex(new File(directoryName))(homeDirPath)
  }
} 
开发者ID:mprzewie,项目名称:cloudia-utils,代码行数:28,代码来源:Index.scala


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


示例3: Directory

//设置package包名称以及导入依赖的类
package akka.stream.alpakka.file.scaladsl

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

import akka.NotUsed
import akka.stream.scaladsl.{Source, StreamConverters}

import scala.collection.immutable

object Directory {

  
  def walk(directory: Path,
           maxDepth: Option[Int] = None,
           fileVisitOptions: immutable.Seq[FileVisitOption] = Nil): Source[Path, NotUsed] = {
    require(Files.isDirectory(directory), s"Path must be a directory, $directory isn't")
    val factory = maxDepth match {
      case None =>
        () =>
          Files.walk(directory, fileVisitOptions: _*)
      case Some(maxDepth) =>
        () =>
          Files.walk(directory, maxDepth, fileVisitOptions: _*)
    }

    StreamConverters.fromJavaStream(factory)
  }

} 
开发者ID:akka,项目名称:alpakka,代码行数:30,代码来源:Directory.scala


示例4: 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"
  }
} 
开发者ID:Madoc,项目名称:create-sbt-project,代码行数:50,代码来源:FileSystemSupport.scala


示例5: SalesforceCustomerRepoSpec

//设置package包名称以及导入依赖的类
package com.ovoenergy.comms.profiles.salesforce

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

import com.ovoenergy.comms.profiles.domain._
import okhttp3._
import org.scalatest.{EitherValues, FlatSpec, Matchers}

class SalesforceCustomerRepoSpec extends FlatSpec with Matchers with EitherValues {

  behavior of "SalesforceCustomerRepo"

  val request = new Request.Builder().url("http://google.com").get().build()

  def buildResponse(code: Int, body: String): (String) => Either[SalesforceError, Response] =
    (str: String) =>
      Right(
        new Response.Builder()
          .protocol(Protocol.HTTP_1_1)
          .code(code)
          .request(request)
          .body(ResponseBody.create(MediaType.parse("application/json"), body))
          .build()
    )

  it should "Successfull deserialise a valid customer json body" in {
    val json =
      new String(Files.readAllBytes(Paths.get("src/test/resources/customer_profile.json")), StandardCharsets.UTF_8)
    val makeAuthenticatedRequest = buildResponse(200, json)
    val profile                  = SalesforceCustomerRepo.getCustomerProfile(makeAuthenticatedRequest)("customer123")
    profile shouldBe Right(
      Customer(
        Name(Some("Mr"), "Gary", "Philpott", None),
        EmailAddresses(Some("[email protected]"), None),
        TelephoneNumbers(Some("+441285112233"), Some("+447834774651"), Some("+441285112233")),
        Embedded(
          List(
            CommunicationPreference("SERVICE", List("Sms", "Email", "POST")),
            CommunicationPreference("MARKETING", List.empty),
            CommunicationPreference("THIRDPARTY", List.empty)
          )
        )
      )
    )
  }

  it should "display an appropriate message if invalid json is returned" in {
    val makeAuthenticatedRequest = buildResponse(200, """{"some": "thing"}""")
    val profile                  = SalesforceCustomerRepo.getCustomerProfile(makeAuthenticatedRequest)("customer123")

    profile.left.value.message should startWith("Invalid JSON from salesforce api")
  }
} 
开发者ID:ovotech,项目名称:comms-profiles,代码行数:55,代码来源:SalesforceCustomerRepoSpec.scala


示例6: Result

//设置package包名称以及导入依赖的类
package org.hammerlab.coverage.one_sample

import java.io.PrintWriter
import java.nio.file.Files

import org.hammerlab.csv._
import org.hammerlab.coverage.Main.getJointHistogramPath
import org.hammerlab.coverage.histogram.JointHistogram
import org.hammerlab.coverage.histogram.JointHistogram.Depth
import org.hammerlab.coverage.utils.{ WriteLines, WriteRDD }
import org.hammerlab.paths.Path
import spire.algebra.Monoid

import scala.reflect.ClassTag
import scala.reflect.runtime.universe.TypeTag

abstract class Result[C: Monoid, CSVRow <: Product : TypeTag : ClassTag]
  extends Serializable {

  def jh: JointHistogram
  def pdf: PDF[C]
  def cdf: CDF[C]
  def filteredCDF: Array[(Depth, C)]

  def toCSVRow(depthCounts: (Depth, C)): CSVRow
  def writeMisc(pw: PrintWriter): Unit

  def save(dir: Path,
           force: Boolean = false,
           writeFullDistributions: Boolean = false,
           writeJointHistogram: Boolean = false): Unit = {

    if (!dir.exists) {
      Files.createDirectories(dir)
    }

    if (writeFullDistributions) {
      WriteRDD(dir / "pdf", pdf.map(toCSVRow), force)
      WriteRDD(dir / "cdf", cdf.map(toCSVRow), force)
    }

    if (writeJointHistogram) {
      val jhPath = getJointHistogramPath(dir)

      if (jhPath.exists) {
        jhPath.delete(recursive = true)
      }

      jh.write(jhPath)
    }

    WriteLines(dir / "cdf.csv", filteredCDF.map(toCSVRow).toCSV(), force)

    val miscPath = dir / "misc"
    if (force || !miscPath.exists) {
      val pw = new PrintWriter(miscPath.outputStream)
      writeMisc(pw)
      pw.close()
    }
  }
} 
开发者ID:hammerlab,项目名称:coverage-depth,代码行数:62,代码来源:Result.scala


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


示例8: LabelReader

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

import java.nio.file.Files

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

import scala.xml.Elem

class LabelReader extends SymbolReader {

  override def loadSymbols(ctx: SymbolReaderContext): Unit = {
    try {
      val labelsFile = ctx.getBaseDir.resolve("labels").resolve("CustomLabels.labels")
      LinkerLog.pushContext(labelsFile.toString)
      if (Files.exists(labelsFile)) {
        LinkerLog.ifNotLogAndThrow(Files.isRegularFile(labelsFile), 0, "Labels file is not a regular file")
        LinkerLog.ifNotLogAndThrow(Files.isReadable(labelsFile), 0, "Labels file is not readable")

        val root = XMLLineLoader.loadFile(labelsFile.toString)
        XMLUtils.ifNotElemLogAndThrow(root, "CustomLabels")

        root.child.foreach {
          case elem: Elem =>
            XMLUtils.ifNotElemLogAndThrow(elem, "labels")
            Label.create(elem).foreach(l => ctx.addLabel(l))
          case _ =>
        }
      }
    } catch {
      case _: LinkerException => () // Ignore, just used to abort processing
    }
  }
} 
开发者ID:nawforce,项目名称:ApexLink,代码行数:34,代码来源:LabelReader.scala


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


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


示例11: FilesLayout

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

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

import eu.tznvy.jancy.modulesgen.discovery.model.ModuleMetadata


class FilesLayout(srcRootPath: Path) {
  //TODO: split path resolving logic and IO in two classes
  def saveModuleSource(moduleMetadata: ModuleMetadata, content: String): Unit = {
    val pathComponents = moduleMetadata.namespace.split('.')
    val outputDirectory = Paths.get(srcRootPath.toString, pathComponents: _*)
    val outputFile = outputDirectory.resolve(moduleMetadata.className + ".java")

    Files.createDirectories(outputDirectory)
    Files.write(outputFile, content.getBytes)
  }
} 
开发者ID:brthanmathwoag,项目名称:jancy,代码行数:19,代码来源:FilesLayout.scala


示例12: LogBack

//设置package包名称以及导入依赖的类
package gitbucket.monitoring.services

import java.nio.file.{Files, Paths}
import scala.xml.XML
import gitbucket.core.util.StringUtil
import gitbucket.monitoring.models.{LogBackInfo}
import gitbucket.monitoring.utils._

object LogBack {
  val notFoundMessage = "Can not find logback configuration file."
  val dosentConfigureMessage = "Dosen't configure Logback."
  val enableLogging = Java.getSystemProperties.contains("logback.configurationFile")
  val confPath = Java.getSystemProperties.getOrElse("logback.configurationFile", notFoundMessage)
  val logBackSettingsFile: Either[String, String] = {
    if (enableLogging) {
      try {
        val bytes = Files.readAllBytes(Paths.get(confPath))
        (Right(
          StringUtil.convertFromByteArray(bytes)
        ))
      } catch {
        case e: Exception => Left(Message.error)
      }
    } else {
      Left(dosentConfigureMessage)
    }
  }

  val logFilePath: Either[String, String] = {
    if (enableLogging) {
      try {
        val xml = logBackSettingsFile match {
          case Left(message) => message
          case Right(s) => {
            (XML.loadString(s) \\ "appender" \ "file" toString).replace("<file>","").replace("</file>","")
          }
        }
        if (xml.trim.length == 0) {
          Left(Message.notFound)
        } else {
          Right(xml)
        }
      } catch {
        case e: Exception => Left(Message.error)
      }
    } else {
      Left(dosentConfigureMessage)
    }
  }

  def getLogBackSettings: LogBackInfo = {
    LogBackInfo(
      Java.getSystemProperties.contains("logback.configurationFile"),
      Java.getSystemProperties.getOrElse("logback.configurationFile", notFoundMessage),
      logFilePath
    )
  }
} 
开发者ID:YoshinoriN,项目名称:gitbucket-monitoring-plugin,代码行数:59,代码来源:LogBack.scala


示例13: SnapshotLogger

//设置package包名称以及导入依赖的类
package se.gigurra.dcs.remote.util

import java.nio.file.{Files, Paths, StandardOpenOption}
import com.twitter.finagle.util.DefaultTimer
import com.twitter.io.Charsets
import com.twitter.util.Duration

case class SnapshotLogger(outputFilePath: String,
                          dtFlush: Duration,
                          enabled: Boolean,
                          fGetSnapshot: () => String) {

  private val path = Paths.get(outputFilePath)

  if (enabled) {
    DefaultTimer.twitter.schedule(dtFlush) {
      Files.write(path, fGetSnapshot().getBytes(Charsets.Utf8), StandardOpenOption.WRITE, StandardOpenOption.CREATE)
    }
  }

} 
开发者ID:GiGurra,项目名称:dcs-remote2,代码行数:22,代码来源:SnapshotLogger.scala


示例14: parseFileIndex

//设置package包名称以及导入依赖的类
import java.io.File
import java.nio.file.StandardCopyOption._
import java.nio.file.Files

if (args.length != 2) {
  println("usage scala upload.scala source-directory destination-directory")
  sys.exit()
}

val source = new File(args(0))
val target = new File(args(1))

def parseFileIndex(lines: Iterator[String]): Map[String, String] =
  lines.map { l => val Array(h, f) = l.split(" ", 2) ; (f, h) }.toMap

// [file -> hash]
def readFileIndex(f: File): Map[String, String] =
  if (f.exists) {
    parseFileIndex(io.Source.fromFile(f).getLines)
  } else {
    Map()
  }

val sf = new File(source, ".files")
val tf = new File(target, ".files")
val sourceIndex = readFileIndex(sf)
val targetIndex = readFileIndex(tf)

for {
  (fn, shash) <- sourceIndex.toSeq.sortBy(_._1)
} {
  val s = new File(source, fn)
  val t = new File(target, fn)

  if (!t.exists() || !targetIndex.contains(fn) || targetIndex(fn) != sourceIndex(fn)) {
    println(s"copying $s -> $t")
    if (t.getParentFile != null) {
      t.getParentFile.mkdirs()
    }
    Files.copy(s.toPath, t.toPath, REPLACE_EXISTING)
  }
}

Files.copy(sf.toPath, tf.toPath, REPLACE_EXISTING)

val thumbSource = new File(source, "t")
val thumbTarget = new File(target, "t")
thumbTarget.mkdirs()

for (s <- thumbSource.listFiles) {
  val t = new File(thumbTarget, s.getName)
  if (!t.exists) {
    println(s"copying $s -> $t")
    Files.copy(s.toPath, t.toPath, REPLACE_EXISTING)
  }
} 
开发者ID:kaja47,项目名称:asciiblog,代码行数:57,代码来源:upload.scala


示例15: MultipartFormDataWritable

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

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

import play.api.http.{HeaderNames, Writeable}
import play.api.libs.Files.TemporaryFile
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.mvc.MultipartFormData.FilePart
import play.api.mvc.{AnyContentAsMultipartFormData, Codec, MultipartFormData}

//Check -> http://tech.fongmun.com/post/125479939452/test-multipartformdata-in-play

object MultipartFormDataWritable {
  val boundary = "--------ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"

  def formatDataParts(data: Map[String, Seq[String]]) = {
    val dataParts = data.flatMap {
      case (key, values) =>
        values.map { value =>
          val name = s""""$key""""
          s"--$boundary\r\n${HeaderNames.CONTENT_DISPOSITION}: form-data; name=$name\r\n\r\n$value\r\n"
        }
    }.mkString("")
    Codec.utf_8.encode(dataParts)
  }

  def filePartHeader(file: FilePart[TemporaryFile]) = {
    val name = s""""${file.key}""""
    val filename = s""""${file.filename}""""
    val contentType = file.contentType.map { ct =>
      s"${HeaderNames.CONTENT_TYPE}: $ct\r\n"
    }.getOrElse("")
    Codec.utf_8.encode(s"--$boundary\r\n${HeaderNames.CONTENT_DISPOSITION}: form-data; name=$name; filename=$filename\r\n$contentType\r\n")
  }

  val singleton = Writeable[MultipartFormData[TemporaryFile]](
    transform = { form: MultipartFormData[TemporaryFile] =>
    formatDataParts(form.dataParts) ++
      form.files.flatMap { file =>
        val fileBytes = Files.readAllBytes(Paths.get(file.ref.file.getAbsolutePath))
        filePartHeader(file) ++ fileBytes ++ Codec.utf_8.encode("\r\n")
      } ++
      Codec.utf_8.encode(s"--$boundary--")
  },
    contentType = Some(s"multipart/form-data; boundary=$boundary")
  )

  implicit val anyContentAsMultipartFormWritable: Writeable[AnyContentAsMultipartFormData] = {
    MultipartFormDataWritable.singleton.map(_.mdf)
  }
} 
开发者ID:Driox,项目名称:play-app-seed,代码行数:52,代码来源:MultiPartFormDataWritable.scala


示例16: FormData

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

import javax.inject._
import java.nio.file.{ Files, Paths }
import play.api._
import play.api.data.Form
import play.api.data.Forms._
import play.api.i18n.MessagesApi
import play.api.mvc._
import com.roundeights.hasher.Implicits._
import dao.FileStore

case class FormData(name: String)


  def index = Action { implicit request ?
    Ok(views.html.index(form, store.archivos()))
  }

  def upload = Action(parse.multipartFormData) { request ?
    request.body.file("archivo").map { archivo ?
      val name = archivo.filename
      val bytes = Files.readAllBytes(archivo.ref.file.toPath)
      val hash = bytes.sha256.hex
      store.store(name, bytes, hash)

      Redirect(routes.HomeController.index).flashing("message" ? "Uploaded")
    }.getOrElse {
      Redirect(routes.HomeController.index).flashing("message" ? "No file")
    }
  }
} 
开发者ID:kdoomsday,项目名称:secStore,代码行数:33,代码来源:HomeController.scala


示例17: 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()
      }
    }

} 
开发者ID:ralreiroe,项目名称:embarcadero,代码行数:40,代码来源:StreamingTest.scala


示例18: HanaActivatorTester

//设置package包名称以及导入依赖的类
import java.io.{BufferedWriter, File, FileWriter}
import java.nio.file.{Files, Paths}


object HanaActivatorTester {
  private val extensions = List("xsapp",
    "xsprivileges",
    "hdbstructure",
    "hdbprocedure",
    "xsjslib",
    "html",
    "hdbrole",
    "xsaccess")

  def main(args: Array[String]): Unit = {
    val workPath = Paths.get(".").toAbsolutePath.normalize.toString
    val filename = "dummy"
    extensions.foreach {
      e =>
        val helloPath = workPath + File.separator + filename + "." + e
        val bw = new BufferedWriter(new FileWriter(new File(helloPath), true))
        bw.write(" ")
        bw.close()
    }
    val workDir = new File(workPath)
    val orderedExtension = workDir.listFiles.toList.sorted(new HanaExtensionComparator)
    extensions.foreach { e =>
      val helloPath = workPath + File.separator + filename + "." + e
      Files.deleteIfExists(Paths.get(helloPath))
    }
  }
} 
开发者ID:janosbinder,项目名称:hana-activator,代码行数:33,代码来源:HanaActivatorTester.scala


示例19:

//设置package包名称以及导入依赖的类
import java.nio.file.{Files, Paths}
import scala.collection.JavaConverters._

val tuples = (0 to 20) // ????????
  .map { // ????????2?N???
    case 0 => 1
    case 1 => 2
    case idx => (0 until idx).foldLeft(2)((s, _) => s * 2)
  }
  .map(n => (n.toString, (BigDecimal(1) / n).bigDecimal.toPlainString)) // 2?N??????

val (maxNum, maxRec) = tuples.last // ??????tuple

val nLen = maxNum.length // ????????????
val rLen = maxRec.length // ????????????

val results = tuples
  .map { case (num, rec) => // ??????
    val numStr = (0 until nLen - num.length).map(_ => ' ').mkString + num
    val recStr = (0 until rLen - rec.length).map(_ => ' ').mkString + rec
    numStr + "    " + recStr
  }

Files.write(Paths.get("results.txt"), results.asJava) // ??????? 
开发者ID:helloscala,项目名称:scala-daily-solution,代码行数:25,代码来源:01.scala


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



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala Http类代码示例发布时间:2022-05-23
下一篇:
Scala Configuration类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap