Kotlin Input Output

www.i‮.aeditfig‬com

In Kotlin, you can perform input and output operations using the standard I/O library, which provides classes and functions to read and write data from the console, files, and other sources.

Here are some examples of input and output operations in Kotlin:

Reading input from the console

To read input from the console, you can use the `readLine()` function, which reads a line of text from the standard input stream and returns it as a string. Here's an example:
fun main() {
    println("Enter your name:")
    val name = readLine()
    println("Hello, $name!")
}

In this example, the program prompts the user to enter their name, reads the input using the readLine() function, and prints a greeting that includes the name.

Writing output to the console

To write output to the console, you can use the `print()` or `println()` functions, which print a string to the standard output stream. The `println()` function adds a newline character at the end of the string. Here's an example:
fun main() {
    println("Hello, world!")
    print("This is a ")
    print("single line ")
    print("of text.")
}

In this example, the program prints two lines of text to the console using the println() function and a single line of text using the print() function.

Reading input from a file

To read input from a file, you can use the `FileReader` class, which reads characters from a file. Here's an example:
import java.io.FileReader

fun main() {
    val reader = FileReader("input.txt")
    val buffer = CharArray(1024)
    reader.read(buffer)
    println(buffer)
    reader.close()
}

In this example, the program creates a FileReader object for the file "input.txt", reads 1024 characters from the file into a character array using the read() method, prints the contents of the array to the console using the println() function, and closes the reader using the close() method.

Writing output to a file

To write output to a file, you can use the `FileWriter` class, which writes characters to a file. Here's an example:
import java.io.FileWriter

fun main() {
    val writer = FileWriter("output.txt")
    writer.write("Hello, world!")
    writer.close()
}

In this example, the program creates a FileWriter object for the file "output.txt", writes the string "Hello, world!" to the file using the write() method, and closes the writer using the close() method. Note that if the file "output.txt" already exists, the FileWriter class will overwrite its contents.