From 232d161e99a2931137d0d5bf31c4537314b97727 Mon Sep 17 00:00:00 2001 From: James Strachan Date: Wed, 21 Dec 2011 10:09:55 +0000 Subject: [PATCH] added a little helper method for processing a closeable object which then makes sure the resource is closed (like the try-with-resource extension in Java 7) --- stdlib/ktSrc/JavaIo.kt | 37 +++++++++++++++++++++++++++++++++++++ testlib/test/HelloWorld.txt | 2 ++ testlib/test/IoTest.kt | 31 +++++++++++++++++++++++++++++++ 3 files changed, 70 insertions(+) create mode 100644 testlib/test/HelloWorld.txt create mode 100644 testlib/test/IoTest.kt diff --git a/stdlib/ktSrc/JavaIo.kt b/stdlib/ktSrc/JavaIo.kt index 71ab785f556..a710dff0c94 100644 --- a/stdlib/ktSrc/JavaIo.kt +++ b/stdlib/ktSrc/JavaIo.kt @@ -67,6 +67,26 @@ namespace io { inline fun readLine() : String? = stdin.readLine() + /** Uses the given resource then closes it to ensure its closed again */ + inline fun T.use(block: fun(T): R) : R { + var closed = false + try { + return block(this) + } catch (e: Exception) { + try { + this.close() + } catch (closeException: Exception) { + // eat the closeException as we are already throwing the original cause + // and we don't want to mask the real exception + } + throw e + } finally { + if (!closed) { + this.close() + } + } + } + fun InputStream.iterator() : ByteIterator = object: ByteIterator() { override val hasNext : Boolean @@ -95,5 +115,22 @@ namespace io { // inline val Reader.buffered : BufferedReader // get() = if(this is BufferedReader) this else BufferedReader(this) + inline fun Reader.buffered() = BufferedReader(this) + inline fun Reader.buffered(bufferSize: Int) = BufferedReader(this, bufferSize) + + inline fun BufferedReader.lineIterator() : Iterator = LineIterator(this) + + protected class LineIterator(val reader: BufferedReader) : Iterator { + var nextLine: String? = null + + override val hasNext: Boolean + get() { + nextLine = reader.readLine() + return nextLine != null + } + + override fun next(): String = nextLine.sure() + } + } \ No newline at end of file diff --git a/testlib/test/HelloWorld.txt b/testlib/test/HelloWorld.txt new file mode 100644 index 00000000000..ed81d07f67b --- /dev/null +++ b/testlib/test/HelloWorld.txt @@ -0,0 +1,2 @@ +Hello +World \ No newline at end of file diff --git a/testlib/test/IoTest.kt b/testlib/test/IoTest.kt new file mode 100644 index 00000000000..2354864bd5b --- /dev/null +++ b/testlib/test/IoTest.kt @@ -0,0 +1,31 @@ +namespace test.collections + +import std.test.* + +import std.io.* +import std.util.* +import java.io.* + +class IoTest() : TestSupport() { + val file = File("test/HelloWorld.txt") + + fun testUse() { + val list = arrayList() + + val reader = FileReader(file).buffered() + reader.close() + + /** + TODO compiler error? + reader.use{ + val line = it.readLine() + if (line != null) { + list.add(line) + } + } + + assertEquals(arrayList("Hello", "World"), list) + */ + } + +} \ No newline at end of file