Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:

How do I get the list of files (or all *.txt files for example) in a directory in Scala. The Source class does not seem to help.

share|improve this question
up vote 31 down vote accepted
new java.io.File(dirName).listFiles.filter(_.getName.endsWith(".txt"))
share|improve this answer

The Java File class is really all you need, although it's easy enough to add some Scala goodness to iteration over directories easier.

import scala.collection.JavaConversions._

for(file <- myDirectory.listFiles if file.getName endsWith ".txt"){
   // process the file
}
share|improve this answer
1  
I tried to edit two little typos, but since it is just two characters, it wouldn't let me. The name of the package is collection, and you are missing a closing parenthesis in your for. – Eduardo Feb 1 '13 at 19:26

The JDK7 version, using the new DirectoryStream class is:

import java.nio.file.{Files, Path}
Files.newDirectoryStream(path).filter(_.endsWith(".txt")).map(_.toAbsolutePath)

Instead of a string, this returns a Path, which has loads of handy methods on it, like 'relativize' and 'subpath'.

Note that you will also need to import import scala.collection.JavaConversions._ to enable interop with Java collections.

share|improve this answer
    
+1 for using java.nio – jasonoriordan Nov 2 '14 at 12:38
1  
I don't know if this has worked in previous versions, but now I get the error ` value map is not a member of java.nio.file.DirectoryStream[java.nio.file.Path] ` – rumtscho Apr 25 at 13:11
    
I get that same error using Java 8 – Peter H May 17 at 22:24
    
It sounds like you need to import the implicit conversions for Java collections: import scala.collection.JavaConversions._ This adds scala methods like map to Java collections, which is great for interop with java libraries (like nio) – Nick Cecil May 20 at 0:08

For now, you should use Java libraries to do so.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.