Created
September 3, 2020 14:53
-
-
Save bseib/79bb7b397fdb9842d1a00d08f18f0200 to your computer and use it in GitHub Desktop.
A clean way to consume an input stream into a buffer using a sequence
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
fun inputStreamToTrimmedString(inputStream: InputStream): String { | |
val baos = ByteArrayOutputStream() | |
val buffer = ByteArray(128) | |
inputStream.bufferedSequence(buffer) { bytesRead -> baos.write(buffer, 0, bytesRead) } | |
return baos.toString("UTF-8").trim() | |
} |
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.InputStream | |
fun InputStream.bufferedSequence(buffer: ByteArray, action: (bytesRead: Int) -> Unit) { | |
this.use { inputStream -> | |
generateSequence { | |
when (val bytesRead = inputStream.read(buffer)) { | |
-1 -> null | |
else -> bytesRead | |
} | |
}.forEach(action) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment