Minor, use "use" to automatically close JarFile

JarFile extends Closeable on JDK 8, so we can use "use" here now
This commit is contained in:
Alexander Udalov
2017-03-29 17:28:18 +03:00
parent cbc893ed17
commit 3b8110f51c
5 changed files with 5 additions and 29 deletions
@@ -77,13 +77,9 @@ class MainClassRunner(override val className: String) : AbstractRunner() {
class JarRunner(private val path: String) : AbstractRunner() {
override val className: String =
try {
val jar = JarFile(path)
try {
JarFile(path).use { jar ->
jar.manifest.mainAttributes.getValue(Attributes.Name.MAIN_CLASS)
}
finally {
jar.close()
}
}
catch (e: IOException) {
throw RunnerException("could not read manifest from " + path + ": " + e.message)
@@ -69,13 +69,9 @@ object LibraryUtils {
if (!library.canRead()) return null
try {
val jarFile = JarFile(library)
try {
JarFile(library).use { jarFile ->
return jarFile.manifest
}
finally {
jarFile.close()
}
}
catch (ignored: IOException) {
return null
@@ -32,16 +32,11 @@ fun main(args: Array<String>) {
fun loadAllFromJar(file: File): Map<String, Pair<JarEntry, ByteArray>> {
val result = hashMapOf<String, Pair<JarEntry, ByteArray>>()
val jar = JarFile(file)
try {
JarFile(file).use { jar ->
for (jarEntry in jar.entries()) {
result[jarEntry.name] = Pair(jarEntry, jar.getInputStream(jarEntry).readBytes())
}
}
finally {
// Yes, JarFile does not extend Closeable on JDK 6 so we can't use "use" here
jar.close()
}
return result
}
@@ -47,8 +47,7 @@ fun loadClassVersions(bytes: ByteArray): Pair<List<Int>, List<Int>>? {
}
fun loadVersions(library: File): String {
val jarFile = JarFile(library)
try {
JarFile(library).use { jarFile ->
for (entry in jarFile.entries()) {
if (entry.name.endsWith(".class")) {
val classBytes = jarFile.getInputStream(entry).readBytes()
@@ -59,10 +58,6 @@ fun loadVersions(library: File): String {
}
}
}
finally {
// Yes, JarFile does not extend Closeable on JDK 6 so we can't use "use" here
jarFile.close()
}
error("No Kotlin classes were found in $library")
}
@@ -19,7 +19,6 @@ import java.io.BufferedOutputStream
import java.io.File
import java.io.FileOutputStream
import java.util.jar.JarFile
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream
/**
@@ -64,8 +63,7 @@ fun main(args: Array<String>) {
ZipOutputStream(BufferedOutputStream(FileOutputStream(outFile))).use {
outJar ->
val inJar = JarFile(inFile)
try {
JarFile(inFile).use { inJar ->
for (entry in inJar.entries()) {
val inBytes = inJar.getInputStream(entry).readBytes()
val outBytes = transform(entry.name, inBytes)
@@ -80,10 +78,6 @@ fun main(args: Array<String>) {
outJar.closeEntry()
}
}
finally {
// Yes, JarFile does not extend Closeable on JDK 6 so we can't use "use" here
inJar.close()
}
}
println("Output written to $outFile")