For reading, there is the useful abstraction Source
. How can I write lines to a text file?
相关问题
- Unusual use of the new keyword
- Get Runtime Type picked by implicit evidence
- What's the point of nonfinal singleton objects
- PlayFramework: how to transform each element of a
- Error in Scala Compiler: java.lang.AssertionError:
相关文章
- Gatling拓展插件开发,check(bodyString.saveAs("key"))怎么实现
- RDF libraries for Scala [closed]
- How to replace file-access references for a module
- Why is my Dispatching on Actors scaled down in Akk
- How do you run cucumber with Scala 2.11 and sbt 0.
- Why is file_get_contents faster than memcache_get?
- GRPC: make high-throughput client in Java/Scala
- Transactionally writing files in Node.js
2019 Update:
Summary - Java NIO (or NIO.2 for async) is still the most comprehensive file processing solution supported in Scala. The following code creates and writes some text to a new file:
Path
object with your chosen file nameOutputStream
write
functionSimilar to the answer by Rex Kerr, but more generic. First I use a helper function:
Then I use this as:
and
etc.
Edit 2019 (8 years later), Scala-IO being not very active, if any, Li Haoyi suggests his own library
lihaoyi/os-lib
, that he presents below.June 2019, Xavier Guihot mentions in his answer the library
Using
, a utility for performing automatic resource management.Edit (September 2011): since Eduardo Costa asks about Scala2.9, and since Rick-777 comments that scalax.IO commit history is pretty much non-existent since mid-2009...
Scala-IO has changed place: see its GitHub repo, from Jesse Eichar (also on SO):
Original answer (January 2011), with the old place for scala-io:
If you don't want to wait for Scala2.9, you can use the scala-incubator / scala-io library.
(as mentioned in "Why doesn't Scala Source close the underlying InputStream?")
See the samples
Unfortunately for the top answer, Scala-IO is dead. If you don't mind using a third-party dependency, consider using my OS-Lib library. This makes working with files, paths and the filesystem very easy:
It has one-liners for writing to files, appending to files, overwriting files, and many other useful/common operations
Similar to this answer, here is an example with
fs2
(version 1.0.4):One liners for saving/reading to/from
String
, usingjava.nio
.This isn't suitable for large files, but will do the job.
Some links:
java.nio.file.Files.write
java.lang.String.getBytes
scala.collection.JavaConverters
scala.collection.immutable.List.mkString