Home > Software design >  Read from file as from console
Read from file as from console

Time:12-04

I am doing a bit of competitive programming in koltin. Most of the time I used input from the console but sometimes I want to use files. Is there a way to make readln() work from a file ? The goal is to avoid writting to code doing the same thing.

From here: Reading console input in Kotlin I tries

fun <T : Closeable, R> T.useWith(block: T.() -> R): R = use { with(it, block) }

File("a.in").bufferedReader().useWith {
    File("a.out").printWriter().useWith {
        val (a, b) = readLine()!!.split(' ').map(String::toInt)
        println(a   b)
    }
}

Scanner(File("b.in")).useWith {
    PrintWriter("b.out").useWith {
        val a = nextInt()
        val b = nextInt()
        println(a   b)
    }
}

But I was not able to make it works.

Thx for any answer.

CodePudding user response:

Yes, you can use the File.forEachLine method to read each line of a file:

val file = File("myfile.txt")
file.forEachLine { line ->
    // Process the line here
    println(line)
}

Alternatively, you can use the FileReader class to explicitly read each line from a file:

val reader = BufferedReader(FileReader("myfile.txt"))
var line = reader.readLine()
while (line != null) {
    // Process the line here
    println(line)
    line = reader.readLine()
}

Both of these examples will read each line of the file and print it to the console.

CodePudding user response:

Thx to @aSemy comment I make it works:

val seq = File("./src/ts1_input.txt").readLines().listIterator() fun readString() = seq.next() // readln()

  • Related