简体   繁体   English

获取目录Java中的文件数量

[英]Getting amount of files in a directory Java

So, I've been trying to count the total amount of elements in a directory. 因此,我一直在尝试计算目录中元素的总数。 It always returns 0. 它总是返回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. 我试过几个目录,其中文件正在计数,但是好了,仍然返回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 是applicationFolder吗

Hi from Java doc we see this: 您好,来自Java文档,我们看到了以下内容:

getRoot() Returns the root component of this path as a Path object, or null if this path does not have a root component. getRoot()返回此路径的根组件作为Path对象;如果此路径没有根组件,则返回null。

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 我也认为这里已经问过这个问题,因此您可以检查此线程

Since you are using Java 8 you can replace: 由于您使用的是Java 8,因此可以替换:

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

...for: ...对于:

Stream.of(applicationFolder.listFiles()).forEach(p -> {
  elements++;
});

I figured it out! 我想到了!

A very clean and good way would be this one: 这是一种非常干净和好的方法:

fileField.listFiles().length

Thanks to everyone for your fast replies! 感谢大家的快速回复!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM