Last active
May 25, 2024 10:20
-
-
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/57a4163af7050bf9310ae2980764b61bf673a8af
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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.4.2" | |
// --------------------- | |
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