1

I'm new to java programming. What I'm trying to achieve is to get file names with a specific pattern that I gather into a String array. I was able to print the results, instead of that, I want to get the file names into a string array so that I can further use the length of the array in the remainder of the program.

File folder = new File("/Test1/Test2/Test3/XYZ03/");
String target_file;
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
    if (listOfFiles[i].isFile()) {
        target_file = listOfFiles[i].getName();
        if (target_file.startsWith("XYZ03") && target_file.endsWith(".dat")) {
            System.out.println("found" + " " + target_file);
            }
       }
 } 
1
  • Have you tried using a List<String> (for example, use ArrayList). You can populate it by doing fileNamesList.add(target_file). Commented Oct 25, 2017 at 11:50

5 Answers 5

3

The new nio classes:

List<String> fileNames = Files.list(Paths.get("/Test1/Test2/Test3/XYZ03"))
    .map(Path::getFileName)
    .map(Path::toString)
    .filter(name -> name.startsWith("XYZ03") && name.endsWith(".dat"))
    .collect(Collectors.toList());

Or as @MalteHartwig commented:

long fileCount = Files.list(Paths.get("/Test1/Test2/Test3/XYZ03"))
    .map(Path::getFileName)
    .map(Path::toString)
    .filter(name -> name.startsWith("XYZ03") && name.endsWith(".dat"))
    .count();

Files.list is a lazy stream (java 8).

Sign up to request clarification or add additional context in comments.

5 Comments

@user1411254 If you only need the count (you said you needed the length of the array), you can replace collect(Collectors.toList()) by count() which gives you the number of matching files right away.
Yes, count gives you the expected number (i.e. after filtering) and avoids creating an extra list. If Op wants an array, they can also use Stream.toArray instead of the collector.
I love this answer. It's a shame that you have to do map twice to obtain the String filename.
@Shirkam or .map(path -> path.getFileName().toString()) (as you probably know) but I went for funcy.
@JoopEggen I almost wrote that, but I didn't like it.
1

If you just want the number of files matching the pattern, a counter variable will help.

int counter = 0;

// your code

if (target_file.startsWith("XYZ03") && target_file.endsWith(".dat")) {
   counter+=1;
}

// counter contains # of files matching that pattern

If you want the file names also, it can be done as follows.

List<String> matchingFiles = new ArrayList<>();

// your code

if (target_file.startsWith("XYZ03") && target_file.endsWith(".dat")) {
   matchingFiles.add(target_file);
}

You can use matchingFiles.size() to get number of files matching the pattern.

If you want to iterate over all such files later, for-each loop will help

for(String matchingFile : matchingFiles) {

  // your work

}    

1 Comment

thanks for all great responses, had to go with @Satish Thulva step since for other answers i had to compile the code over Java Ver6 which we are not using
0

You can use list to store file name, string array was not useful, because the size of array should be declared. But in case of List no size is required.

    List<String> list = new ArrayList<String>();   // Using list
    for (int i = 0; i < listOfFiles.length; i++) 
    {
      if (listOfFiles[i].isFile()) 
      {
       list.add(listOfFiles[i].getName();
      }
    }

Comments

0

You can use ArrayList for the purposes where you don't know how many objects you are going to store.

    List<String> validFileNames = new ArrayList<>();// Here we declare the list
    File[] listOfFiles = folder.listFiles();
    for (int i = 0; i < listOfFiles.length; i++) {
        if (listOfFiles[i].isFile()) {
            target_file = listOfFiles[i].getName();
            if (target_file.startsWith("XYZ03") && target_file.endsWith(".dat")) {
                System.out.println("found" + " " + target_file);
                validFileNames.add(target_file); // Here we add the names to the list
            }
        }
    }

You can then decide to return/use the arraylist itself or to make an array out of it.

String[] fileNamesArray = (String[])validFileNames.toArray();

Comments

0

You can use an ArrayList instead of an array. It will save some space. ArrayList expands itself when needed. You won't necessarily need to provide the initial size of the list. Here's the link to the documentation of ArrayList.

// created an ArrayList  
List<String> matchingFiles = new ArrayList<>();

File folder = new File("/Test1/Test2/Test3/XYZ03/");
String target_file;
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
      if (listOfFiles[i].isFile()) {
 target_file = listOfFiles[i].getName();
  if (target_file.startsWith("XYZ03") && target_file.endsWith(".dat")) {
        // as simple as that
        matchingFiles.add(target_file);
     }
   }
} 

for (String matchingFile : matchingFiles) {
    // do whatever you want
} 

Comments

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.