How to get file list in array using java?

825 views Asked by At

i`m trying to get file name from directory as array.

i want:

List<String> list = ["c:/MyFolder/file1.txt", "c:/MyFolder/file2.txt"];

Then i can get then like:

println list[0] //c:/MyFolder/file1.txt
println list[1] //c:/MyFolder/file2.txt

how can i have filenames is array from this code?

import java.io.File;


public class FileListFromFolder {
     
    public static void main(String a[]){
        File file = new File("C:/MyFolder/");
        String[] fileList = file.list();
        for(String name:fileList){
            System.out.println(name);
        }
    }
}

Thank you

2

There are 2 answers

1
hitesh bedre On BEST ANSWER

This might help you

public class FileListFromFolder {
 
    public static void main(String a[]) {
      File file = new File("C:/MyFolder/");
      String[] fileList = file.list();
      List<String> arrayToList = Arrays.asList(fileList);
      System.out.println(arrayToList);
   }
}
0
Александар Красић On
      File file = new File("C:/MyFolder/");
      File[] fileList = file.listFiles();
      for(File f:fileList){
         System.out.println(f.getName());
      }


This is the way to iterate over a list of files in directory and to print their names.