2

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

mypetlion
  • 2,415
  • 5
  • 18
  • 22
  • What exactly does not work with that code? `list();` returns an array of strings representing the paths of the files and folders contained in the instance of `File` on which you call it. Which as far as I can tell is what you want. – JustAnotherDeveloper Aug 26 '20 at 20:30
  • Method `Arrays.asList(T[] arr)` converts input array to list. – Nowhere Man Aug 26 '20 at 20:34
  • Do you want to get a list of files in a directory? There are answers for this: https://stackoverflow.com/questions/1844688/how-to-read-all-files-in-a-folder-from-java – NomadMaker Aug 26 '20 at 20:47

2 Answers2

0

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);
   }
}
hitesh bedre
  • 459
  • 2
  • 11
0
      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.