使用Java计算目录中的文件数 [英] Counting the number of files in a directory using Java

查看:121
本文介绍了使用Java计算目录中的文件数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Java计算目录中的文件数?为了简单起见,我们假设目录没有任何子目录。

How do I count the number of files in a directory using Java ? For simplicity, lets assume that the directory doesn't have any sub-directories.

我知道标准方法:

new File(<directory path>).listFiles().length

但是,这将有效地通过目录中的所有文件,如果文件数量很大,可能需要很长时间。此外,我不关心目录中的实际文件,除非它们的数字大于一些固定的大数字(例如5000)。

But this will effectively go through all the files in the directory, which might take long if the number of files is large. Also, I don't care about the actual files in the directory unless their number is greater than some fixed large number (say 5000).

我猜,但目录(或Unix的i节点)是否存储其中包含的文件数?如果我可以把这个数字从文件系统中拿走,那会更快。在后端开始进行真正处理之前,我需要对Tomcat服务器上的每个HTTP请求进行此检查。因此,速度至关重要。

I am guessing, but doesn't the directory (or its i-node in case of Unix) store the number of files contained in it? If I could get that number straight away from the file system, it would be much faster. I need to do this check for every HTTP request on a Tomcat server before the back-end starts doing the real processing. Therefore, speed is of paramount importance.

我可以每隔一段时间运行一个守护程序来清除目录。我知道,所以请不要给我这个解决方案。

I could run a daemon every once in a while to clear the directory. I know that, so please don't give me that solution.

推荐答案

这可能不适合你的应用程序,但你可以随时尝试本机调用(使用jni或 jna ),或执行特定于平台的命令,并阅读输出后才回到list()。在* nix上,你可以执行 ls -1a | wc -l <​​/ code>(注意 - 这是第一个命令的dash-one-a,第二个命令为dash-lowercase-L)。不知道在Windows上是什么 - 可能只是一个 dir 并查找摘要。

This might not be appropriate for your application, but you could always try a native call (using jni or jna), or exec a platform-specific command and read the output before falling back to list().length. On *nix, you could exec ls -1a | wc -l (note - that's dash-one-a for the first command, and dash-lowercase-L for the second). Not sure what would be right on windows - perhaps just a dir and look for the summary.

在烦恼之前像这样的事情我强烈建议您创建一个文件数量非常多的目录,只需查看list()。长度确实需要太长时间。如此博客所建议的,您可以不想出汗。

Before bothering with something like this I'd strongly recommend you create a directory with a very large number of files and just see if list().length really does take too long. As this blogger suggests, you may not want to sweat this.

我可能会跟Varkhan的回答自己一起。

I'd probably go with Varkhan's answer myself.

这篇关于使用Java计算目录中的文件数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆