如何在scala中创建文件和文件夹并写入?我理解它在其他语言中是如何工作的,但Scala有点棘手:/
这与其他问题不同,因为它还询问如何在Scala中创建目录和文件。
答案 0 :(得分:6)
保罗·菲利普斯刚才在ML上提到了一个问题,“我写了一个包含java.nio.file.Path的文件库”,所以你应该等着看看他想出了什么。
与此同时,他之前关于java.io的工作已经像一个不安分的精神一样徘徊,但现在出没了:
scala> import reflect.io._
import reflect.io._
scala> val f = File("my-test.txt")
f: scala.reflect.io.File = my-test.txt
scala> f writeAll ("hello", ",", " ", "world", "\n")
scala> :q
apm@mara:~/tmp$ cat my-test.txt
hello, world
还有Path
和Directory
的抽象。
scala> val d = Directory(".")
d: scala.reflect.io.Directory = .
scala> d.list
res0: Iterator[scala.reflect.io.Path] = non-empty iterator
scala> d.deepList()
res2: Iterator[scala.reflect.io.Path] = non-empty iterator
scala> d.deepFiles.toList
res4: List[scala.reflect.io.File] = List(./mkarray.scala, ./for29.scala, ./nofunc-wrapped.scala, ./inlined.scala, ./xmlex.scala, ./pet.scala, ./lookup.scala, ./CompilerTool.scala, ./badvargs.scala, ./tz0.scala, ./discontinuations.jar, ./serious.scala, ./badjunk.scala, ./version.scala, ./shapeless_2.11.jar, ./callbacks.scala, ./delayed.scala, ./privctor0.scala, ./nestedtags.scala, ./hw-repl.scala, ./schema-one.txt, ./tstest.scala, ./badimp.scala, ./matchprim.scala, ./sxemata-all.txt, ./arrow.scala, ./continuations2.jar, ./inliner.scala, ./oneq.scala, ./impmag.scala, ./enumuser.scala, ./auto.save, ./xmlregex.scala, ./strtyp.scala, ./orelse.scala, ./scalac-plugin.xml, ./futuremap.scala, ./applied.save, ./looker.scala, ./pat1, ./sounds.scala, ./shapeless_2.10.jar, ./funkstr.scala, ./stupid....
scala> val p = Path(".")
p: scala.reflect.io.Path = .
scala> val f = p / "mkarray.scala"
f: scala.reflect.io.Path = ./mkarray.scala