简体   繁体   English

无法在 Kotlin 中将字符串解析为文件

[英]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抱歉代码不好我是 Kotlin 的初学者

You'll kick yourself… :-)你会踢自己…… :-)

To create a File object, you simply call its constructor , eg File("/path/to/myFile") .要创建File对象,您只需调用其构造函数,例如File("/path/to/myFile") (There are other constructors which let you specify a directory and a filename separately, or a URI.) (还有其他构造函数可让您分别指定目录和文件名或 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!) (当您将其转换为生产代码时,您处理 I/O 错误,我敢肯定!)

Kotlin provides other ways to read a file; Kotlin 提供了其他读取文件的方法; take a look at extension functions like File.useLines , File.readLines , and File.forEachLine which make it even easier.看看像File.useLinesFile.readLinesFile.forEachLine这样的扩展函数,它们使它变得更加容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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