简体   繁体   English

在具有大量Java文件的目录中获取文件列表

[英]Getting the list of files within a directory that has lots of files in java

Will using the list() method in the File class give issues if its a directory with thousands of files in it? 如果文件目录中包含成千上万个文件,在File类中使用list()方法会产生问题吗? Could this cause the array returned to use too much memory? 这会导致返回的数组使用过多的内存吗?

What alternative is there? 有什么选择吗?

Unlikely. 不太可能。 You should be just fine using File.list() . 使用File.list()应该很好。 Thousands of file names is not much in terms of memory. 就内存而言,成千上万个文件名并不多。

As for alternatives, there aren't any "better ways" to do it in Java and as I already said, you probably won't need them. 至于替代方案,在Java中没有任何“更好的方法”可以做到,而且正如我已经说过的那样,您可能不需要它们。

import java.io.*;
import java.util.*;

public class prog14{
    public static void main(String[] args){
        String path = "";
        System.out.print("Enter the folder path: ");
        Scanner scn = new Scanner(System.in);
        path = scn.nextLine();
        File[] files = new File(path).listFiles();
        for (File file : files) 
        {
            System.out.println(file.getName());
        }
    }
}

Unlikely (this would amount to allocating a few megabytes, top). 不太可能(这相当于分配几个兆字节,顶部)。 Try it first, search for workarounds only if it is a real issue :) 请先尝试,仅在存在实际问题时才搜索解决方法:)

I may be wrong about this, but surely there is no possible way to economise the amount of data returned. 我对此可能是错的,但是肯定没有任何方法可以节省返回的数据量。 The returned array will always use the the amount of bytes needed to store the same number of strings as there are files in the directory. 返回的数组将始终使用存储与目录中的文件相同数量的字符串所需的字节数。 The only ways I can see to reduce memory usage are to use some complex string compression technique or just organise your files into folders and then use the list method on only the ones you need to. 我看到的减少内存使用的唯一方法是使用一些复杂的字符串压缩技术,或者只是将文件组织到文件夹中,然后仅在需要的文件上使用list方法。 Hope that helps. 希望能有所帮助。

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

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