使用 java,从文件夹位置提取列表文件名的最节省资源的方法是什么
Using java, what is the most resource efficient way to pull a list files names from a folder location
使用 Java,从文件夹位置提取 'list' 个文件名的最节省资源的方法是什么。目前我正在使用以下代码:-
File[] files = new File(folderLocation).listFiles();
在遍历文件数组并仅将文件名转储到我的应用程序要使用的哈希中之前。所以,请记住,我只需要文件名,有没有更节省内存的方法来做到这一点。
编辑:
- 我没有使用 Java 7
- 我实际上并没有遇到内存错误,但我开发的方法花费了很长时间 运行(20 分钟),这对于我正在开发的应用程序来说不是一个现实的选择。
使用Java 7+有:
final Path dir = Paths.get(folderLocation);
final List<String> names = new ArrayList<>();
try (
final DirectoryStream<Path> dirstream
= Files.newDirectoryStream(dir);
) {
for (final Path entry: dirstream)
list.add(entry.getFileName());
}
你可以查看Path
在 javadoc 中提到
Path getFileName()
Returns the name of the file or directory denoted by this path as a Path object
您可以使用返回 String[] 的 (new File(folderLocation)).list()
。每个字符串都是路径+分隔符+文件名。您可以从此字符串中提取文件名。
是否需要区分文件和目录。如果没有,您可以使用 File 中的 list() 函数来 return 一个字符串数组,命名该抽象路径名表示的目录中的文件和目录。然后,您可以轻松地使用该列表构造一个 HashSet。例如,
String[] files = new File(folderLocation).list();
Set<String> mySet = new HashSet<String>(Arrays.asList(files));
还有一个 list(FilenameFilter filter) 函数,它接受文件名过滤器和 returns 字符串名称列表。但是,它不允许您根据 file/directory.
进行过滤
使用 Java,从文件夹位置提取 'list' 个文件名的最节省资源的方法是什么。目前我正在使用以下代码:-
File[] files = new File(folderLocation).listFiles();
在遍历文件数组并仅将文件名转储到我的应用程序要使用的哈希中之前。所以,请记住,我只需要文件名,有没有更节省内存的方法来做到这一点。
编辑:
- 我没有使用 Java 7
- 我实际上并没有遇到内存错误,但我开发的方法花费了很长时间 运行(20 分钟),这对于我正在开发的应用程序来说不是一个现实的选择。
使用Java 7+有:
final Path dir = Paths.get(folderLocation);
final List<String> names = new ArrayList<>();
try (
final DirectoryStream<Path> dirstream
= Files.newDirectoryStream(dir);
) {
for (final Path entry: dirstream)
list.add(entry.getFileName());
}
你可以查看Path
在 javadoc 中提到
Path getFileName()
Returns the name of the file or directory denoted by this path as a Path object
您可以使用返回 String[] 的 (new File(folderLocation)).list()
。每个字符串都是路径+分隔符+文件名。您可以从此字符串中提取文件名。
是否需要区分文件和目录。如果没有,您可以使用 File 中的 list() 函数来 return 一个字符串数组,命名该抽象路径名表示的目录中的文件和目录。然后,您可以轻松地使用该列表构造一个 HashSet。例如,
String[] files = new File(folderLocation).list();
Set<String> mySet = new HashSet<String>(Arrays.asList(files));
还有一个 list(FilenameFilter filter) 函数,它接受文件名过滤器和 returns 字符串名称列表。但是,它不允许您根据 file/directory.
进行过滤