我需要閱讀一個文本檔案,readLines()我已經找到了這個問題,但答案中的代碼總是使用一些變體javaClass;它似乎只在一個類中作業,而我只使用一個沒有宣告類的簡單 Kotlin 檔案。像這樣寫在語法上是正確的,但它看起來真的很丑,而且總是回傳null,所以它一定是錯誤的:
val lines = object {}.javaClass.getResource("file.txt")?.toURI()?.toPath()?.readLines()
當然我可以像這樣指定原始路徑,但我想知道是否有更好的方法:
val lines = File("src/main/resources/file.txt").readLines()
uj5u.com熱心網友回復:
Kotlin 沒有自己的獲取資源的方法,所以你必須使用 Java 的方法Class.getResource。你不應該假設資源是一個檔案(即不要使用toPath),因為它很可能是 jar 中的一個條目,而不是檔案系統上的檔案。要讀取資源,更容易將資源作為 an 獲取InputStream,然后從中讀取行:
val lines = this::class.java.getResourceAsStream("file.txt").bufferedReader().readLines()
uj5u.com熱心網友回復:
我不確定我的回答是否試圖回答您的確切問題,但也許您可以這樣做:
我猜在最后一個用例中,檔案名將是動態的 - 不是靜態宣告的。在這種情況下,如果您有權訪問或知道檔案夾的路徑,則可以執行以下操作:
// Create an extension function on the String class to retrieve a list of
// files available within a folder. Though I have not added a check here
// to validate this, a condition can be added to assert if the extension
// called is executed on a folder or not
fun String.getFilesInFolder(): Array<out File>? = with(File(this)) { return listFiles() }
// Call the extension function on the String folder path wherever required
fun retrieveFiles(): Array<out File>? = [PATH TO FOLDER].getFilesInFolder()
一旦你有了List<out File>物件的參考,你就可以做這樣的事情:
// Create an extension function to read
fun File.retrieveContent() = readLines()
// You can can further expand this use case to conditionally return
// readLines() or entire file data using a buffered reader or convert file
// content to a Data class through GSON/whatever.
// You can use Generic Constraints
// Refer this article for possibilities
// https://kotlinlang.org/docs/generics.html#generic-constraints
// Then simply call this extension function after retrieving files in the folder.
listOfFiles?.forEach { singleFile -> println(singleFile.retrieveContent()) }
uj5u.com熱心網友回復:
感謝這個答案提供了讀取檔案的正確方法。目前,javaClass似乎不可能在不使用或類似結構的情況下從資源中讀取檔案。
// use this if you're inside a class
val lines = this::class.java.getResourceAsStream("file.txt")?.bufferedReader()?.readLines()
// use this otherwise
val lines = object {}.javaClass.getResourceAsStream("file.txt")?.bufferedReader()?.readLines()
根據我發現的其他類似問題,第二種方法可能也適用于 lambda,但我尚未對其進行測驗。請注意從這一點開始需要?.運算子和lines?.let {}語法,因為如果沒有找到具有給定名稱的資源,則getResourceAsStream()回傳null。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/385102.html
上一篇:具有開放功能的生成器理解
