Last active
May 8, 2017 02:14
-
-
Save j5ik2o/052541b4925faa97c561b1adbc70c441 to your computer and use it in GitHub Desktop.
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
import java.io._ | |
import java.nio.charset.StandardCharsets | |
object LoarnMain extends App { | |
def getFileBody(file: String): String = | |
using(new FileInputStream(file)) { fis => | |
val text = new Array[Byte](fis.available) | |
fis.read(text) | |
new String(text, StandardCharsets.UTF_8) | |
} | |
println(getFileBody("package.json")) | |
} |
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
import java.io._ | |
import java.nio.charset.StandardCharsets | |
def using[A: Disposer, B](resource: A)(f: A => B): B = | |
try { | |
f(resource) | |
} finally { | |
implicitly[Disposer[A]].dispose(resource) | |
} | |
trait Disposer[-A] { | |
def dispose(resource: A): Unit | |
} | |
object Disposer { | |
import java.io._ | |
// InputStreamのサブ型であればどの実装でもストリームを閉じることができる | |
implicit val inputStreamDisposer = new Disposer[InputStream] { | |
override def dispose(resource: InputStream): Unit = | |
resource.close() | |
} | |
// OutputStreamのサブ型にも対応した場合は、以下を参考する。 | |
// implicit val outputStreamDisposer = new Disposer[OutputStream] { | |
// override def dispose(resource: OutputStream): Unit = | |
// resource.close() | |
// } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment