diff --git a/CHANGELOG.org b/CHANGELOG.org index fa0944e..d3f4d19 100644 --- a/CHANGELOG.org +++ b/CHANGELOG.org @@ -12,6 +12,7 @@ The format is based on [[https://keepachangelog.com/en/1.0.0/][Keep a Changelog] - Log copy and delete operations (#119) - Log errors with red label (#119) + - Ensure file handles are always closed (#122) ** Changed diff --git a/core/src/main/scala/net/kemitix/thorp/core/MD5HashGenerator.scala b/core/src/main/scala/net/kemitix/thorp/core/MD5HashGenerator.scala index 3972846..2977e92 100644 --- a/core/src/main/scala/net/kemitix/thorp/core/MD5HashGenerator.scala +++ b/core/src/main/scala/net/kemitix/thorp/core/MD5HashGenerator.scala @@ -5,7 +5,7 @@ import java.nio.file.Path import java.security.MessageDigest import net.kemitix.thorp.domain.MD5Hash -import zio.Task +import zio.{Task, UIO, ZManaged} import scala.collection.immutable.NumericRange @@ -47,22 +47,22 @@ object MD5HashGenerator { offset: Long, endOffset: Long ) = - for { - fis <- openFile(file, offset) - digest <- digestFile(fis, offset, endOffset) - _ <- closeFile(fis) - } yield digest + openFile(file, offset) + .use(digestFile(_, offset, endOffset)) private def openFile( file: File, offset: Long - ) = Task { - val stream = new FileInputStream(file) - stream skip offset - stream - } + ) = + ZManaged.make { + Task { + val stream = new FileInputStream(file) + stream skip offset + stream + } + }(closeFile) - private def closeFile(fis: FileInputStream) = Task(fis.close()) + private def closeFile(fis: FileInputStream) = UIO(fis.close()) private def digestFile( fis: FileInputStream,