2017-06-14 58 views
1

我正在閱讀「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中執行這個簡單的任務(打開目錄的文本文件)?

+0

請參閱[java.nio.Files](https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html)。有很多'Path'的靜態方法。例如'readAllLines(Path path,Charset cs)'。 – saka1029

回答

0

您可以讀取目錄並過濾其中的所有目錄,並通過打開它來處理每個文件。下面是簡單的例子

val dirname: String = "/path" 

    val files = new File(dirname) 

    files.listFiles().filter(!_.isDirectory).map{ 
    file => process the file 
    } 

希望這有助於!

+0

工作,謝謝!我改爲「文件處理」與「io.Source.fromFile(文件).mkString」進行測試,它按預期工作。 – ahstat

+0

Thankyou爲upvote和接受爲答:) –