Welcome to CodeYourCraft's Kotlin InputStream and OutputStream tutorial! In this lesson, we'll delve into the world of streams, learning how to read and write data to various sources like files, network connections, and even memory.
InputStream and OutputStream are fundamental classes in Kotlin's Java-compatible standard library. They represent streams of bytes and are used for reading and writing data.
Let's see how to read data from a file using an InputStream.
import java.io.FileInputStream
import java.io.File
fun main() {
val file = File("example.txt")
val inputStream = FileInputStream(file)
// Reading the file line by line
inputStream.bufferedReader().lines().forEach { println(it) }
inputStream.close()
}š Note: In the above example, we first create a File object for our text file, example.txt. Then, we create an InputStream using the FileInputStream constructor. To read the file line by line, we wrap the InputStream in a BufferedReader and use the lines function to iterate over each line. Lastly, we close the InputStream to release any resources it's holding.
Now, let's write data to a file using an OutputStream.
import java.io.FileOutputStream
import java.io.File
fun main() {
val file = File("output.txt")
val outputStream = FileOutputStream(file)
// Writing text to the file
outputStream.write("Hello, World!\n".toByteArray())
outputStream.close()
}š Note: Here, we create a FileOutputStream instance for our output file, output.txt. We convert our text string to bytes using the toByteArray() function and write the data to the file using the write() function. Lastly, we close the OutputStream to save the data to the file.
For more advanced usage, you can read and write data in chunks or handle exceptions for better error handling.
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.IOException
fun main() {
val inputFile = File("input.bin")
val outputFile = File("output.bin")
val inputStream: InputStream
val outputStream: OutputStream
try {
inputStream = FileInputStream(inputFile)
outputStream = FileOutputStream(outputFile)
val buffer = ByteArray(1024)
var bytesRead: Int
while (true) {
bytesRead = inputStream.read(buffer)
if (bytesRead <= 0) break
outputStream.write(buffer, 0, bytesRead)
}
inputStream.close()
outputStream.close()
} catch (e: IOException) {
println("An error occurred: ${e.message}")
}
}š Note: In this example, we read data from input.bin and write it to output.bin in chunks of 1024 bytes. We handle exceptions using the try-catch block to catch any potential errors.
What are the main differences between InputStream and OutputStream?