Lifecycle lifecycle 6.
Io6.1.
File I/O6.1.1.
Read files
Scala is unique to Scala. Io. source, for example:
Import scala. Io ._
Source. fromfile ("cn. Scala", "utf8"). mkstring
Read object content row by row:
Source. fromfile(New java. Io. File ("cn. Scala ")). Getlines (). foreach (println)
6.1.2.
Write files
Directly call Java IO:
Import java. Io. _, java. NiO. channels. _, java. NiO ._
// Write an object
Val F = new fileoutputstream ("o.txt"). getchannel
F write bytebuffer. Wrap ("a little bit long...". getbytes)
F close
Or:
VaR out = new java. Io. filewriter ("./out.txt") // filewriter ("./out.txt", true) is the append mode.
Out. Write ("Hello \ n ")
Out close
6.1.3.
Copy a file
Directly call Java IO:
Val in = new fileinputstream ("in"). getchannel
Val out = new fileoutputstream ("out"). getchannel
In transferto (0, In. Size, out)
6.2.
Network I/O
import java.net.{URL, URLEncoder} import scala.io.Source.fromURL
fromURL(new URL("http://qh.appspot.com")).mkString
Or specify the encoding:
fromURL(new URL("http://qh.appspot.com"))(io.Codec.UTF8).mkString
Scala Io stream operations