0

So, I've been trying to count the total amount of elements in a directory. It always returns 0.

This is my code:

public int getElementsInDirectory() {
    Path path = Paths.get(applicationFolder.getAbsolutePath());
    Logger.log("Directory", "Absoloute path: " + path);
    if(path == null) {
        Logger.log("Directory", "Path doesn't exist");
        return 0;
    }
    Paths.get(applicationFolder.getAbsolutePath()).getRoot().forEach(p -> {
        elements++;
    });
    return elements;
}

I've tried several directories where the files are being counted, but well, still returns to 0.

And the best part is, the path is also not null, as this is the output

 [2015-07-25, Directory] Created folder!
 [2015-07-25, Directory] Absoloute path: C:\Users\Yasin

So it's pretty much finding the path correctly, now it's just the elements.

Oh yeah, almost forgot:

new File(System.getProperty("user.home") + "/");

Is applicationFolder

Sh0ck
  • 97
  • 2
  • 12
  • How about adding a `System.out.println()` inside the forEach to see if it is even going inside it? Other option is to run this using a debugger. – Neo Jul 24 '15 at 23:37

3 Answers3

0

Hi from Java doc we see this:

getRoot() Returns the root component of this path as a Path object, or null if this path does not have a root component.

Which means that your code will definitely not do what you are expecting. Also I think that this question was already asked here so you can check this thread

Community
  • 1
  • 1
ap0calypt1c
  • 481
  • 4
  • 10
0

Since you are using Java 8 you can replace:

Paths.get(applicationFolder.getAbsolutePath()).getRoot().forEach(p -> {
  elements++;
});

...for:

Stream.of(applicationFolder.listFiles()).forEach(p -> {
  elements++;
});
x80486
  • 6,627
  • 5
  • 52
  • 111
0

I figured it out!

A very clean and good way would be this one:

fileField.listFiles().length

Thanks to everyone for your fast replies!

Sh0ck
  • 97
  • 2
  • 12
  • `File.list().length` might be more efficient as this is a `String` array instead of `File` array – Neo Jul 24 '15 at 23:47
  • Oh thank you very much!!!, but why should I use static context though? I'm trying to prevent static access – Sh0ck Jul 24 '15 at 23:59
  • It (`list()`) is an `instance` method. Just wanted to highlight the class the method is on. – Neo Jul 25 '15 at 01:33