Skip to content

Instantly share code, notes, and snippets.

@Nikaoto
Last active July 27, 2020 09:31
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Nikaoto/75cdc5d9609cddc8a4df7a01282d4e03 to your computer and use it in GitHub Desktop.
Save Nikaoto/75cdc5d9609cddc8a4df7a01282d4e03 to your computer and use it in GitHub Desktop.
A function 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