Created
December 8, 2016 13:08
-
-
Save RichardBradley/bcd1a5e61fcc83e4e59f8b9b0bc2301c to your computer and use it in GitHub Desktop.
Demo code for http://stackoverflow.com/questions/6879427/scala-write-string-to-file-in-one-statement
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
import java.io.{FileInputStream, IOException, InputStream} | |
import java.nio.charset.StandardCharsets | |
import java.nio.file.{Files, Paths} | |
import scala.io.Source | |
object q5221524 { | |
def main(args: Array[String]): Unit = { | |
// Setup | |
Files.write( | |
Paths.get("test.txt"), | |
"test".getBytes(StandardCharsets.UTF_8)) | |
def isClosed(s: InputStream): Boolean = | |
try { | |
s.available() | |
false | |
} catch { | |
case e: IOException | |
if e.getMessage.contains("Stream Closed") => | |
true | |
} | |
// Tests: | |
val is = new FileInputStream("test.txt") | |
assert(!isClosed(is)) | |
println(Source.fromInputStream(is).mkString("")) | |
assert(!isClosed(is)) | |
is.close() | |
assert(isClosed(is)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment