Site icon DataFlair

Input Output in Kotlin

kotlin input output

Job-ready Online Courses: Click, Learn, Succeed, Start Now!

Kotlin is a statically typed programming language renowned for its extensive support for input and output operations. Whether you require user input, file processing, or data display, Kotlin provides a range of efficient mechanisms to fulfill these requirements. This article offers an exploration of Kotlin’s input and output features, accompanied by proper code examples and explanations to help you understand their implementation.

Input Output in Kotlin

1. Reading User Input in Kotlin:

One common programming task involves reading input from users. Kotlin offers several approaches to accomplish this, including the utilization of the `readLine()` function and the Scanner class.

Example 1: Using readLine()

fun main() {
    print("Enter your name: ")
    val name = readLine()
    println("Hello, $name!")
}

Output

Enter your name: Mugdha
Hello, Mugdha!

In the provided code snippet, the `readLine()` function captures the user’s input as a string, which is then stored in the `name` variable. Subsequently, the program prints a greeting message along with the entered name.

Example 2: Using Scanner

import java.util.Scanner

fun main() {
    val scanner = Scanner(System.`in`)
    print("Enter your age: ")
    val age = scanner.nextInt()
    println("You are $age years old.")
}

Output

Enter your age: 25
You are 25 years old.

In this example, the Scanner class is employed to read an integer value from the user. The `nextInt()` function reads the entered integer, which is stored in the `age` variable and later displayed to the user.

2. Writing Output in Kotlin:

Kotlin offers various methods for displaying information to users or saving data to files. Some commonly used methods include `print()`, `println()`, and `writeText()`.

Example 3: Using print() and println() 

fun main() {
    val name = "John"
    val age = 25
    print("Name: $name, Age: $age")
    println("Gender: Female")
}

Output

Name: Mugdha, Age: 25 Gender: Female

In the provided example, the `print()` and `println()` functions are utilized to display information. The placeholders `$name` and `$age` are replaced with their respective values.

Example 4: Writing to a File in Kotlin

import java.io.File

fun main() {
    val text = "Hello, DataFlair!"
    File("output.txt").writeText(text)
    println("Data written to the file.")
}

Output

Data written to the file.

This code snippet demonstrates writing text to a file using the `writeText()` function from the File class. The specified text is written to a file named “output.txt”. Finally, a message confirming the successful write operation is displayed.

3. File Operations in Kotlin:

Kotlin provides a rich set of functions and classes for handling file operations, such as reading from and writing to files.
The File class is commonly used for such operations.

Example 5: Reading from a File in Kotlin

import java.io.File

fun main() {
    val file = File("input.txt")
    val content = file.readText()
    println("File content: $content")
}

Output

File content: This is the content of the input file.

In this example, a File object representing the file “input.txt” is created. The `readText()` function reads the entire content of the file, which is then stored in the `content` variable. Finally, the content is printed on the console.

Example 6: Appending to a File in Kotlin

import java.io.File

fun main() {
    val file = File("output.txt")
    val text = "New line of text"
    file.appendText(text)
    println("Text appended to the file.")
}

Output

Text appended to the file.

In this example, the `appendText()` function is employed to append the specified text to an existing file. Then the program displays a message confirming the successful operation.

Difference Between println() and print() in Kotlin

The println() function is used to print a line of text and then move to the next line. On the other hand, the print() function is used to print text without moving to the next line.

When to use println():

Use println() when you want to display a line of text and move to the next line.
It is useful for separating different outputs or for improving readability.

When to use print():

Use print() when you want to display text without moving to the next line.
It is handy when you want to display multiple outputs on the same line or when you want to control the layout of your output.

Conclusion:

In this comprehensive guide, we explored the input and output capabilities of Kotlin. We learned various methods to read user input using functions like readLine() and the Scanner class. Additionally, we discovered techniques to write output to the console and files using print(), println(), and writeText(). We also discussed the difference between println() and print(). Lastly, we explored file-related operations, including reading from files and appending text to existing files using the File class. Armed with this knowledge, you can effectively handle input and output operations in Kotlin and develop robust applications with user interaction and data manipulation capabilities.

Happy Coding! 🙂

Exit mobile version