Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active April 2, 2023 10:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dacr/7822b63f3640747a5c5f0ca1acfb08ed to your computer and use it in GitHub Desktop.
Save dacr/7822b63f3640747a5c5f0ca1acfb08ed to your computer and use it in GitHub Desktop.
Using scala default API for operations with files. / published by https://github.com/dacr/code-examples-manager #193b27c7-caf5-4938-b2c9-a853c68aacd0/1c3dd8fb73e02ccaa1d7cd482b75d0f2ac9197e8
// summary : Using scala default API for operations with files.
// keywords : scala, file, io
// publish : gist
// authors : David Crosson
// license : Apache NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2)
// id : 193b27c7-caf5-4938-b2c9-a853c68aacd0
// created-on : 2020-05-31T19:54:52Z
// managed-by : https://github.com/dacr/code-examples-manager
// run-with : scala-cli $file
// ---------------------
//> using scala "3.1.1"
// ---------------------
import scala.io.Source
import java.io.{File, FileOutputStream, PrintStream}
def fileContent(file: File): String = Source.fromFile(file).getLines().mkString("\n")
def cwd1:String = System.getProperty("user.dir")
def cwd2:String = new File(".").getCanonicalPath
println("------------- list files -----------------")
new File(s"$cwd1/example/").list().filter(_.endsWith(".md")).foreach(println)
println("------------- read file -----------------")
val content = fileContent(new File(s"$cwd1/example/index.md"))
println(content)
println("------------- write file -----------------")
val newContent =
"""# Some new title
|with some content
|""".stripMargin
val tmpFile = File.createTempFile("tmpfile", ".tmp")
val output = new PrintStream(new FileOutputStream(tmpFile))
output.print(newContent)
output.flush()
output.close()
val checkContent = fileContent(tmpFile)
assert( checkContent.trim == newContent.trim)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment