Skip to content

Yet another programming solutions log

Sample bits from programming for the future generations.

Technologies Technologies
  • Algorithms and Data Structures
  • Java Tutorials
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Spock Framework Tutorial
  • Spring Framework
  • Bash Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Developer’s Tools
  • Productivity
  • About
Expand Search Form

Java File list files

farenda 2016-02-09 0

Problem:

How to list files in Java? In this post we’re going to show how to use File class to list files and do name filtering using FilenameFilter.

Solution:

In the following example we’re going to list files in a directory. If the program is run without any arguments then it list all files in the current directory (“.”). When only one argument is given it is treated as a path of directory to list. If you provide the second argument it is assumed to be a RegExp pattern of files to show.

package com.farenda.java.io;

import java.io.File;
import java.io.FilenameFilter;
import java.util.Arrays;
import java.util.regex.Pattern;

public class FileListFilesExample {

    private static class RegExpFilter implements FilenameFilter {

        private final Pattern pattern;

        public RegExpFilter(String pattern) {
            this.pattern = Pattern.compile(pattern);
        }

        @Override
        public final boolean accept(File file, String name) {
            return pattern.matcher(name).matches();
        }
    }

    // The first arg is dir, the second one (if any) files pattern.
    public static void main(final String[] args) {
        File dir = selectDirectory(args);

        String[] names = getFileNames(dir, args);

        System.out.println("Files and directories in "
                + dir.getAbsolutePath());
        for (String file : names) {
            System.out.println(file);
        }
    }

    private static File selectDirectory(String[] args) {
        // current or given as program param
        return (args.length == 0) ? new File(".") : new File(args[0]);
    }

    private static String[] getFileNames(File dir, String[] args) {
        String[] names;
        if (args.length > 1) {
            names = dir.list(new RegExpFilter(args[1]));
        } else {
            names = dir.list();
        }

        // Sort just for better readability
        Arrays.sort(names);

        return names;
    }
}

As you can see there are two methods to list files: File.list() and File.list(FilenameFilter). The first one just list all files, but the second one takes java.io.FilenameFilter as its parameter and shows only the names for which accept(File file, String name) method returned true.

Let’s see the code in action!

List all files in “/boot” directory:

$> java -classpath /out com.farenda.java.io.FileListFilesExample /boot

Files and directories in /boot
System.map-4.2.0-27-generic
abi-4.2.0-27-generic
config-4.2.0-27-generic
grub
initrd.img-4.2.0-27-generic
memtest86+.bin
memtest86+.elf
memtest86+_multiboot.bin
vmlinuz-4.2.0-27-generic

List all files in “/etc” directory that start with pass string:

$> java -classpath /out com.farenda.java.io.FileListFilesExample /etc pass.*

Files and directories in /etc
passwd
passwd-
Share with the World!
Categories Java Tags java, java-io
Previous: Java File – display space on disk
Next: Java write text file

Recent Posts

  • Java 8 Date Time concepts
  • Maven dependency to local JAR
  • Caesar cipher in Java
  • Java casting trick
  • Java 8 flatMap practical example
  • Linked List – remove element
  • Linked List – insert element at position
  • Linked List add element at the end
  • Create Java Streams
  • Floyd Cycle detection in Java

Pages

  • About Farenda
  • Algorithms and Data Structures
  • Bash Tutorial
  • Bean Validation Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Java 8 Streams and Lambda Expressions Tutorial
  • Java Basics Tutorial
  • Java Collections Tutorial
  • Java Concurrency Tutorial
  • Java IO Tutorial
  • Java Tutorials
  • Java Util Tutorial
  • Java XML Tutorial
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Software Developer’s Tools
  • Spock Framework Tutorial
  • Spring Framework

Tags

algorithms bash bean-validation books clojure design-patterns embedmongo exercises git gof gradle groovy hateoas hsqldb i18n java java-basics java-collections java-concurrency java-io java-lang java-time java-util java-xml java8 java8-files junit linux lists log4j logging maven mongodb performance quartz refactoring regex rest slf4j solid spring spring-boot spring-core sql unit-tests

Yet another programming solutions log © 2022

sponsored