Title Image

Modified : 2023/10/08

コンソールでのテキストやパスワードの入力

Kotlinでコンソール(console)からテキストやパスワードの入力を行う方法を紹介します。
[Kotlin]に戻る

[記事の先頭]

コンソールでのテキスト入力(readLine()版)

 簡単なコードでテキスト入力を行うサンプルです。
 入力をお願いするメッセージ(1行目)と入力テキストの行(2行目)が異なります。

サンプルコード

fun inputText1(message: String): String {
    println(message)

    val text = readLine()
    return text ?: ""
}

text = inputText("名前を入力してください。 : ")
println("あなたのお名前は「$text」さんですね。")

サンプルコードの実行結果

名前を入力してください。 : 
Apricot Tail
あなたのお名前は「Apricot Tail」さんですね。
[記事の先頭]

コンソールでのテキスト入力(System.console()版)

 System.console()を使ったテキスト入力を行うサンプルです。
 入力をお願いするメッセージと入力テキストの行(1行目)が同じになります。

サンプルコード

fun inputText2(message: String): String {
    var text = ""

    val console = System.console()
    if (console != null) {
        text = console.readLine(message)
    }

    return text
}

text = inputText2("名前を入力してください。 : ")
println("あなたのお名前は「$text」さんですね。")

サンプルコードの実行結果

名前を入力してください。 : Apricot Tail
あなたのお名前は「Apricot Tail」さんですね。
[記事の先頭]

コンソールでのパスワード入力(System.console()版)

 System.console()を使ったパスワード入力を行うサンプルです。
 入力をお願いするメッセージと入力パスワードの行(1行目)が同じになります。

サンプルコード

fun inputPassword2(message: String): String {
    var password = ""

    val console = System.console()
    if (console != null) {
        val passwordArray = console.readPassword(message)
        password = String(passwordArray)
    }

    return password
}

pw = inputPassword("パスワードを入力してください。 : ")
println("入力したパスワードは${pw.length}文字ですね。")

サンプルコードの実行結果

パスワードを入力してください。 : ← 表示されないが「test」と入力
入力したパスワードは4文字ですね。
[記事の先頭]

関連記事

[記事の先頭]
[Kotlin]に戻る