Last active
April 2, 2023 10:13
-
-
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
This file contains 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.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