0

Hello members of stackoverflow

I need some help with adding files from a directory to a bunch of files (File[])

So basically i want to add all the files in a directory to the following group of files:

File[] contents = {};

The user of my application will select a directory and i want that directories contents to be added to the above group of files ('contents I'm not sure how this is done because it doesn't have a simple 'add' method like an ArrayList/List does.

Any help with this would be greatly appreciated.

Thanks.

1
  • If you want to be able to easily add to a list after it's created, use a List, not an array. Commented Oct 26, 2013 at 23:00

2 Answers 2

2

Use File.listFiles():

File dir = new File("/somedir");
File[] files = dir.listFiles();
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for this, didn't realize it was such a simple solution. I was trying to use a for loop to add files but this is much better :)
Taking a look at the API documentation is always helpful.
1
    try
    {
        File folder = new File(FOLDER_NAME);
        File[] contents = folder.listFiles();
    }
    catch(Exception e) 
    {
        System.out.println("[Error] Folder not Found"); 
    }

5 Comments

Could you elaborate ?
The File constructor throws only a NullPointerException when the argument is null. On the other hand listFiles throws a SecurityException. None of the exceptions say anything about the file/directory not being found.
The constructor is not validating the path. From doc - It "Creates a new File instance by converting the given pathname string into an abstract pathname." So even File f = new File(""); will execute without throwing any exception.
Nope, just checked again. It throws an exception if you have an incorrect path. Try it yourself once.
I doubt. Why do you think then File.exists() method is there for?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.