Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding file names to an array list in java

Tags:

java

file

I am currently needing to load the contents of a folders filenames to an arraylist I have but I am unsure as how to do this.

To put it into perspective I have a folder with One.txt, Two.txt, Three.txt etc. I want to be able to load this list into an arraylist so that if I was to check the arraylist its contents would be :

arraylist[0] = One

arraylist[1] = Two

arraylist[3] = Three

If anyone could give me any insight into this it would be much appreciated.

like image 799
Chris G Avatar asked Dec 17 '22 01:12

Chris G


1 Answers

Here's a solution that uses java.io.File.list(FilenameFilter). It keeps the .txt suffix; you can strip these easily if you really need to.

File dir = new File(".");
List<String> list = Arrays.asList(dir.list(
   new FilenameFilter() {
      @Override public boolean accept(File dir, String name) {
         return name.endsWith(".txt");
      }
   }
));
System.out.println(list);
like image 81
polygenelubricants Avatar answered Dec 21 '22 10:12

polygenelubricants