How to Filter Files 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 File[] files = sampleDir.list((pathname) -> pathname.getName().length() > 2); // longer than 2 characters

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

  }

}

JDK 7

import static java.lang.System.out;

import java.io.File;
import java.io.FileFilter;

public final class JdkSample {

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

    final File[] files = sampleDir.list(new FileFilter() {

      public boolean accept(final File pathname) {
        return pathname.getName().length() > 2;
      }

    });

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

  }

}

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