How to get contents of a folder and put into an ArrayList

后端 未结 5 1042
滥情空心
滥情空心 2020-12-14 06:10

I want to use

File f = new File(\"C:\\\\\");

to make an ArrayList with the contents of the folder.

I am not very good with buffered

相关标签:
5条回答
  • 2020-12-14 06:36

    Streams are fast and very easy to read:

    final Path rootPath = Paths.get("/tmp");
    
    // All entries Path objects
    ArrayList<Path> all = Files
            .list(rootPath)
            .collect(Collectors.toCollection(ArrayList::new));
    
    // Only regular files at Path objects
    ArrayList<Path> regularFilePaths = Files
            .list(rootPath)
            .filter(Files::isRegularFile)
            .collect(Collectors.toCollection(ArrayList::new));
    
    // Only regular files as String paths
    ArrayList<String> regularPathsAsString = Files
            .list(rootPath)
            .filter(Files::isRegularFile)
            .map(Path::toString)
            .collect(Collectors.toCollection(ArrayList::new));
    
    0 讨论(0)
  • 2020-12-14 06:37

    If you want to retrieve all the files recursively, you can do something like below

    public class FileLister {
    
        static List<String> fileList = new ArrayList<String>();
    
        public static void main(String[] args) {
            File file = new File("C:\\tmp");
            listDirectory(file);
            System.out.println(fileList);
        }
    
        public static void listDirectory(File file) {
            if(file.isDirectory()) {
                File[] files = file.listFiles();
                for(File currFile : files) {
                    listDirectory(currFile);
                }
            }
            else {
                fileList.add(file.getPath());
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-14 06:38

    The easiest way of doing that is:

    File f = new File("C:\\");
    ArrayList<File> files = new ArrayList<File>(Arrays.asList(f.listFiles()));
    

    And if what you want is a list of names:

    File f = new File("C:\\");
    ArrayList<String> names = new ArrayList<String>(Arrays.asList(f.list()));
    
    0 讨论(0)
  • 2020-12-14 06:45

    Have you read the API documentation for java.io.File?

    File f = new File("C:\\");
    File[] list = f.listFiles();
    
    0 讨论(0)
  • 2020-12-14 06:56

    The File-class offers a listFiles()-method which returns a File-array of all files in the current folder.

    To make an ArrayList of them, you can use the Arrays-class and it's asList()-method. See here.

    If you only need the file-names or paths as Strings, there is also a list()-method which returns a String-array. To convert the array to an ArrayList, follow the steps illustrated in the linked question.

    0 讨论(0)
提交回复
热议问题