要讀取文件的全部行,能夠調用scala.io.Source對象的getLines方法:html
import scala.io.Source val source = Source.fromFile("myfile.txt", "UTF-8") val lineIterator = source.getLines val lines1 =lineIterator.toArray val lines2 = lineIterator.toBuffer //將文件內容讀成字符串 val lines = source.mkString source.close
val iter = source.buffered while(iter.hasNext){ if(iter.next == '王'){ println("wang") }else{ println("-") } }
val iter 2= source.mkString.split("\\s+") val num = for(w <- iter2) yield w.toDouble for(i <- num) println(i)
val source1 = Source.fromURL("http://baidu.com")//URL讀取 val source2 = Source.fromString("hello")//讀取給定的字符串-多用於調試 import scala.io.StdIn val ms=StdIn.readLine()
import java.io.{File, FileInputStream} val file = new File(" ") val in = new FileInputStream(file) val bytes = new Array[Byte](file.length.toInt) in.read(bytes) in.close()
val out = new PrintWriter("numbers.txt") for (i <- 1 to 100) { out.println(i) out.print(f"$quantity%6d $price%10.2f") } out.close()
import java.nio.file._ val dirname = "/home/cay/scala-impatient/code" val entries = Files.walk(Paths.get(dirname)) // or Files.list try { entries.forEach(p => println(p)) } finally { entries.close() }
@SerialVersionUID(42L) class Person extends Serializable{} class Person extends Serializable { private val friends = new ArrayBuffer[Person] // OK—ArrayBuffer is serializable } val fred = new Person(...) import java.io._ val out = new ObjectOutputStream(new FileOutputStream("/tmp/test.obj")) out.writeObject(fred) out.close() val in = new ObjectInputStream(new FileInputStream("/tmp/test.obj")) val savedFred = in.readObject().asInstanceOf[Person]
import scala.sys.process._ "ls -al ..".! ("ls -al /" #| "grep u").! #輸出重定向到文件 ("ls -al /" #> new File("filelist.txt")).! #追加到末尾 ("ls -al /etc" #>> new File("filelist.txt")).! #把某個文件的內容做爲輸入 ("grep u" #< new File("filelist.txt")).! #從URL重定向輸入 ("grep Scala" #< new URL("http://horstmann.com/index.html")).!