1

I have this much so far

 import java.io.File;
 import java.io.FilenameFilter;
 import java.util.ArrayList;
 import java.util.Arrays;

 import org.pdfbox.util.Splitter;
 public class fileName {
     public static void main(String args[]){
         File file = new File("/Users/apple/Desktop/");
         String[] directories = file.list(new FilenameFilter(){

             @Override
             public boolean accept(File current, String name) {
                return new File(current, name).isDirectory();
             }
         });
 System.out.println(Arrays.toString(directories));
 ArrayList<String[]>SSOList = new ArrayList<String[]>();
     }
 }

It prints the names of all the files on my desktop but I want to add them to an arraylist. How do I do that?

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
DylanK
  • 15
  • 3

3 Answers3

1

It is very easy. You can use recursion as follows:

 private static void read(final File folder)  {

    for (final File fileEntry : folder.listFiles()) {
        if (fileEntry.isDirectory()) {
            read(fileEntry);
        } else {
       //Do something
            }
    }
}
lonesome
  • 2,503
  • 6
  • 35
  • 61
1

There are quite a few ways by which you can get the filenames in an ArrayList:

  1. Use the Arrays.asList() method:

ArrayList<String> SSOList = new ArrayList<String>(Arrays.asList(directories));

  1. Use the Collections utility class allAll method:

    List<String> SSOList = new ArrayList<String>(directories.length); Collections.addAll(SSOList , directories);

  2. Traverse the directories array again and add each value to the ArrayList SSOList.

Kepping in mind that these are to be done after you get the values in directories array.

srp321
  • 116
  • 2
  • 10
0
ArrayList<String> SSOList =  new ArrayList<String>(Arrays.asList(directories))

or you can use:

Collections.addAll(SSOList, directories);

Also if SSOList is the name of the ArrayList you want the files to be stored in, I think you need to change it to an array list of Strings and not array list of array of Strings :

List<String>SSOList = new ArrayList<String>();
slal
  • 2,657
  • 18
  • 29