Recent Changes - Search:

Oktatás

* Programozás 1
  + feladatsor
  + GitHub oldal

* Szkriptnyelvek
  + feladatsor
  + quick link

Teaching

* Programming 1 (BI)
  ◇ exercises
  ◇ quick link

* Scripting Languages
  ◇ exercises
  ◇ quick link

teaching assets


Félévek

* aktuális (2023/24/2)
* archívum


Linkek

* kalendárium
   - munkaszüneti napok '20
* tételsorok
* jegyzetek
* szakdolgozat / PhD
* ösztöndíjak
* certificates
* C lang.
* C++
* C#
* Clojure
* D lang.
* Java
* Nim
* Scala


[ edit | logout ]
[ sandbox | passwd ]

file operations

#############################

Read a file line by line

import scala.io.Source

def main() {
  val fname = "island.txt"
  val src = Source.fromFile(fname, "utf-8")    // Open file. Omit encoding if the file uses the platform's default encoding.
  for (line <- src.getLines) {                 // getLines is an iterator
    println(line)                              // line has no newline at its end
  }
  src.close                                    // Close file. Don't forget it!
}

Read the lines into an Array

  val fname = "island.txt"
  val src = Source.fromFile(fname, "utf-8")
  val lines = src.getLines.toArray             // read the whole content into an array
  src.close                                    // close it

  println(lines.mkString(", "))                // visualize the content of the array
  println("Number of lines: %d.".format(lines.length))

Instead of an Array you can read into an ArrayBuffer too.

Read the file's entire content into a string

def main() {
  val fname = "island.txt"
  val src = Source.fromFile(fname, "utf-8")
  val content = src.mkString                   // content to string
  src.close                                    // close it

  println(content)
}

Read a file char by char

def main() {
  val fname = "island.txt"
  val src = Source.fromFile(fname, "utf-8")
  for (c <- src) {
    print(c)
  }
  src.close
}

Process a file word by word

def main() {
  val fname = "island.txt"
  val src = Source.fromFile(fname, "utf-8")
  for (line <- src.getLines) {
    for (w <- line.split("\\s+")) {            // split the line by whitespaces
      println(w)
    }
  }
  src.close
}

Writing to a file

import java.io.PrintWriter

def main() {
  val out = new PrintWriter("out.txt")         // notice the "new" operator
  for (i <- 1 to 10) {
    out.println(i)
  }
  out.println("__END__")
  out.close                                    // close it
}

For writing, Scala borrows PrintWriter from Java.

Cloud City

  

Blogjaim, hobbi projektjeim

* The Ubuntu Incident
* Python Adventures
* @GitHub
* heroku
* extra
* haladó Python
* YouTube listák


Debrecen | la France


[ edit ]

Edit - History - Print *** Report - Recent Changes - Search
Page last modified on 2015 March 14, 20:47