Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading files from a directory in Scala

Tags:

scala

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.

like image 323
snappy Avatar asked Dec 24 '11 02:12

snappy


People also ask

How do I read a Scala file in Windows?

getlines it will first an non – empty iterator of string data type and then traversing will print the elements aside. The take() function take the line element we want to read it from that read file. So the take(1), (2), (3) will take the elements from the file and print that accordingly.

How do I read a resource folder in eclipse?

In Java, we can use getResourceAsStream or getResource to read a file or multiple files from a resources folder or root of the classpath. The getResourceAsStream method returns an InputStream . // the stream holding the file content InputStream is = getClass().

How do I delete a folder in Scala?

We use the delete method, which works similarly to deleteRecursively method, returning a boolean true for success and false for failure. As a result, this implementation will go through every file in every directory under the leading directory, deleting every file.


2 Answers

new java.io.File(dirName).listFiles.filter(_.getName.endsWith(".txt")) 
like image 132
huynhjl Avatar answered Oct 16 '22 02:10

huynhjl


The JDK7 version, using the new DirectoryStream class is:

import java.nio.file.{Files, Path} Files.newDirectoryStream(path)     .filter(_.getFileName.toString.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.

like image 34
Nick Cecil Avatar answered Oct 16 '22 01:10

Nick Cecil