2

How can I make files and folders in scala and write to them? I understand how it works in other languages, but Scala is a bit trickier :/

This is different than the other question because it also asks how to make directories and files in Scala.

vsingal5
  • 304
  • 5
  • 18

1 Answers1

6

Paul Phillips just mentioned parenthetically on ML, "I wrote a library which does a bunch of wrapping of java.nio.file.Path", so you should wait to see what he came up with.

In the meantime, his previous work on java.io has wandered like a restless spirit but now haunts:

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

There are also abstractions for Path and 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
som-snytt
  • 39,429
  • 2
  • 47
  • 129