• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 230
  • Last Modified:

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.
0
meow00
Asked:
meow00
  • 5
  • 3
1 Solution
 
CEHJCommented:
Just list the directory

File[] petsFiles = new File("Animal").listFiles();
String[] petNames = new String[petsFiles.length];
// Now copy just the name into petNames
0
 
meow00Author Commented:
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.
0
 
CEHJCommented:
You can use a FileFilter


File[] petsFiles = new File("Animal").listFiles(new FileFilter() {
    public boolean accept(File f) {
        return f.getName().toLowerCase().endsWith(".pet");
    }
});
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
meow00Author Commented:
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 ...:-(
0
 
CEHJCommented:
File[] petsFiles = new File(".").listFiles(new FileFilter() {
0
 
meow00Author Commented:
thanks so much ... one last question ... how do I copy the name before .pet to the new array ? thanks.
0
 
CEHJCommented:
You could do both things at the same time actually:


String[] petNames = null;
List petNamesList = new ArrayList();
File[] petsFiles = new File("Animal").listFiles(new FileFilter() {
    public boolean accept(File f) {
          String name = f.getName();
          String[] parts = name.split("\\.");
          if ("pet".equalsIgnoreCase(parts[parts.length - 1])) {
                petNamesList.add(parts[parts.length - 2]);
                return true;
          }
          else {
                return false;
          }
    }
});
if (petNamesList.size() > 0) {
      petNames = (String[])petNamesList.toArray(new String[petNamesList.size()]);
}
0
 
CEHJCommented:
:-)
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

  • 5
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now