tags:

views:

346

answers:

6

Hi

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.

A: 

You can try with

File folder = new File("myfolder");

if (folder.isDirectory())
{
  // you can get all the names
  String[] fileNames = folder.list();

  // you can get directly files objects
  File[] files = folder.listFiles();
}
Jack
This is the first approach I looked at and it worked perfectly for what I needed. I wasn't aware of the isDirectory method within the File class. I guess it serves me right for not looking properly at the API. Anyway thanks for the example.
Chris G
A: 

See the Jave File API, particularly the list() function.

File my_dir = new File("DirectoryName");
assert(my_dir.exists()); // the directory exists
assert(my_dir.isDirectory()); // and is actually a directory

String[] filenames_in_dir = my_dir.list();

Now filenames_in_dir is an array of all the filenames, which is almost precisely what you want.

If you want to strip the extensions off the individual filenames, that's basic string handling - iterate over the filenames and take care of each one.

Ziv
+1  A: 
File dir = new File("/some/path/name");
List<String> list = new ArrayList<String>();
if (dir.isDirectory()) {
  String[] files = dir.list();
  Pattern p = Pattern.compile("^(.*?)\\.txt$");
  for (String file : files) {
    Matcher m = p.matcher(file);
    if (m.matches()) {
      list.add(m.group(1));
    }
  }
}
cletus
Thanks alot for yours and every one elses quick responses.. Its much appreciated! I will look into these answers when I get home. Thanks :)
Chris G
A: 

Have a look at java.io.File it gives you all the control you may need. Here is a URL for it http://java.sun.com/j2se/1.5.0/docs/api/java/io/File.html

Neer
Thanks for the link =-) had a little look. I really should have looked at that before asking :/ my bad
Chris G
+2  A: 

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);
polygenelubricants
A: 

it is very help full know array list

arul