Skip to content

Instantly share code, notes, and snippets.

@xingstarx
Forked from Nikaoto/CopyBytes.kt
Created June 15, 2018 10:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xingstarx/43565b78d3c1ac4972d32575677e2f1c to your computer and use it in GitHub Desktop.
Save xingstarx/43565b78d3c1ac4972d32575677e2f1c to your computer and use it in GitHub Desktop.
A method that copies data from input to output (in Kotlin and Java)
void copyBytes(InputStream input, OutputStream output) throws IOException {
//Creating byte array for copying the data
byte[] buffer = new byte[1024];
int length = input.read(buffer);
//Transferring data
while (length != -1) {
output.write(buffer, 0, length);
length = input.read(buffer);
}
//Finalizing
output.flush();
output.close();
input.close();
}
//A Kotlin object (singleton) that handles the copying with mulitple different arguments
object CopyBytes {
@Throws(IOException::class)
fun copy(input: InputStream, output: OutputStream) {
//Creating byte array
val buffer = ByteArray(1024)
var length = input.read(buffer)
//Transferring data
while(length != -1) {
output.write(buffer, 0, length)
length = input.read(buffer)
}
//Finalizing
output.flush()
output.close()
input.close()
}
//In - String, Out - Stream
fun copy(input: String, output: OutputStream) {
copy(FileInputStream(input), output)
}
//In - Stream, Out - String
fun copy(input: InputStream, output: String) {
copy(input, FileOutputStream(output))
}
//In - String, Out - String
fun copy(input: String, output: String) {
copy(FileInputStream(input), FileOutputStream(output))
}
}
@Throws(IOException::class)
fun copyBytes(input: InputStream, output: OutputStream) {
//Creating byte array
val buffer = ByteArray(1024)
var length = input.read(buffer)
//Transferring data
while(length != -1) {
output.write(buffer, 0, length)
length = input.read(buffer)
}
//Finalizing
output.flush()
output.close()
input.close()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment