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.
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.
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().
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.
new java.io.File(dirName).listFiles.filter(_.getName.endsWith(".txt"))
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With