简体   繁体   中英

Can't parse String to File in Kotlin

This is basic script where you input a file as one of the arguments and based on it's extension it executes it with a different program. This is not the full code this just the code that is giving me an error:

package com.pavlos.efstathiou.runScript

import java.io.BufferedReader
import java.io.File
import java.util.logging.Level.parse

fun main(args: Array<String>) {
    val filename: Any = args[0]
    if (args.isEmpty()) println("No arguments provided")
    if (args.size > 2) println("Too many arguments provided")
    fun read() {
        val filenameString = File.parse(filename) // I don't know what function to use to parse the filename String
        val reader: BufferedReader = filenameString.bufferedReader()
        val inputString = reader.use { it.readText() }
        println("Contents of file: $inputString")

    }
}

The only problem is that I can't parse the function's argument which is a String to a file name. Sorry for the bad code I am a beginner in Kotlin

You'll kick yourself… :-)

To create a File object, you simply call its constructor , eg File("/path/to/myFile") . (There are other constructors which let you specify a directory and a filename separately, or a URI.)

A File is an abstract representation of the filename; it can be absolute (starting with / or whatever the root of your filesystem is), or relative (to the current directory). The file doesn't even need to exist.

Of course, if not, then you'll get an error when you try to create a reader for it in the following line. (You will be handling I/O errors when you convert that into production code, I'm sure!)

Kotlin provides other ways to read a file; take a look at extension functions like File.useLines , File.readLines , and File.forEachLine which make it even easier.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM