How to Filter File Names with Oracle JDK

JDK 8

import static java.lang.System.out;

import java.io.File;

public final class JdkSample {

  public static void main(final String[] args) {
    final File sampleDir = new File("sample");

    final String[] fileNames = sampleDir.list((dir, name) -> name.length() > 2); // longer than 2 characters

    for (int i = 0; i < fileNames.length; i++)
      out.println(fileNames[i]);

  }

}

JDK 7

import static java.lang.System.out;

import java.io.File;
import java.io.FilenameFilter;

public final class JdkSample {

  public static void main(final String[] args) {
    final File sampleDir = new File("sample");

    final String[] fileNames = sampleDir.list(new FilenameFilter() {

      public boolean accept(final File dir, final String name) {
       return name.length() > 2;
      }

    });

    for (int i = 0; i < fileNames.length; i++)
      out.println(fileNames[i]);

  }

}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s