Link to home
Start Free TrialLog in
Avatar of meow00
meow00

asked on

read files from a directory ...

Hello experts,

   I have several files such as:

   dog.pet, cat.pet, bird.pet, elephant.pet ...etc., all in the "Animal" folder.
  There are also files called ant.bad, fly.bad ... etc. in the Animal folder as well.

   How do I open the *.pet files, read some info in the file, and then store the filename (eg. dog, cat ...) in to an array ?
   I mean I want an array storing : dog, cat, bird, elephant ... etc.
   And of course, I don't know how many files in Animal are "*.pet" files at very beginning ...

   Is this something possible ? thanks.
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Just list the directory

File[] petsFiles = new File("Animal").listFiles();
String[] petNames = new String[petsFiles.length];
// Now copy just the name into petNames
Avatar of meow00
meow00

ASKER

but there are ant.bad & fly.bad in the Animal folder as well ...
And I don't want *.bad files ...

Also, what is the files are in the current folder, how do I call the .listFiles() function ??? thanks.
You can use a FileFilter


File[] petsFiles = new File("Animal").listFiles(new FileFilter() {
    public boolean accept(File f) {
        return f.getName().toLowerCase().endsWith(".pet");
    }
});
Avatar of meow00

ASKER

I see, thanks...

What do I do if the files are in the current folder (same folder as the main program)

File[] petsFiles = new File("").listFiles();  or
File[] petsFiles = new File().listFiles();
 doesn't seem to work ...:-(
File[] petsFiles = new File(".").listFiles(new FileFilter() {
Avatar of meow00

ASKER

thanks so much ... one last question ... how do I copy the name before .pet to the new array ? thanks.
ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
:-)