ps0604
ps0604

Reputation: 1081

How to detect a Java File Walk is a file or a folder (in Scala)?

I have the following code in Scala that returns a tree of directories and files

import java.nio._
import java.nio.file._
import collection.JavaConverters._

object TestFileWalk extends App {
  val dir = FileSystems.getDefault.getPath("c://app-files") 
  Files.walk(dir).iterator().asScala.foreach(println)
}

Running the code above returns:

c:\app-files
c:\app-files\csv
c:\app-files\csv\10
c:\app-files\csv\10\Book2.csv
c:\app-files\csv\11
c:\app-files\csv\11\Book3.txt
c:\app-files\csv\12
c:\app-files\csv\9
c:\app-files\csv\9\Book1.csv
c:\app-files\csvtemp
c:\app-files\csvtemp\user1
c:\app-files\csvtemp\user1\script 2016-11-04.sql
c:\app-files\This is a folder with Uppercase
c:\app-files\This is a folder with Uppercase\File in the folder with Uppercase.csv

As you can see, some entries are folder names and others file names (files have extension).

How can I programmatically know if the entry is a file or a folder? I looked at Path but cannot figure it out.

Upvotes: 0

Views: 584

Answers (1)

GhostCat
GhostCat

Reputation: 140613

That call

val dir = FileSystems.getDefault.getPath("c://app-files") 

returns a Path object ( see here for details ).

And the Path class provides a method [toFile()][2]; return a File object. From there: the File class contains [isDirectory()][2]

Thus:

dir.toFile().isDirectory()

gives you what you are looking for!

And beyond that:

Files.walk(dir).iterator().asScala.foreach(println)

walk(dir).iterator() results in Iterator<Path>; so again - you have a Path object there; which you could transform into a File; and a File knows if it is a directory or not!

Upvotes: 1

Related Questions