我正在閱讀「Scala for the impatient」(第二版),我被困在如何訪問目錄(第9.7節)。Scala訪問目錄
我想依次打開目錄中的所有文件(不包括該目錄中存在的文件夾;這些文件是文本文件)。 書中提供的示例並不簡單,因爲它沒有解釋如何處理路徑中的物體(java.nio.file.Path)
這裏是在書(略有修改)的例子:
import java.nio.file._
val dirname: String = "./9_files_and_regular_expressions"
val entries = Files.list(Paths.get(dirname))
entries.toArray // print all the file names and consume the iterator...
val entries = Files.list(Paths.get(dirname))
try {
entries.forEach(p => process the path p)
} finally {
entries.close()
}
而不是「處理路徑p」,我想打開相關的目錄......我在這裏看到的文檔https://docs.oracle.com/javase/7/docs/api/java/nio/file/Path.html,但這個包看起來非常低的水平。我是否需要將路徑轉換爲文件首先,然後處理這個文件對象?
有沒有更簡單的方法來在Scala中執行這個簡單的任務(打開目錄的文本文件)?
請參閱[java.nio.Files](https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html)。有很多'Path'的靜態方法。例如'readAllLines(Path path,Charset cs)'。 – saka1029