FilenameUtils

org.apache.commons.io.FilenameUtils Example

Apache Commons IO is a library of utilities to assist with developing IO functionality. org.apache.commons.io package has utility classes to perform common tasks. FilenameUtils is one of the classes. This class has static methods for filename and filepath manipulation. This class aims to help avoid those problems related with moving file names used in unix and Windows environments.

This article shows usage of some methods defined in this class.

The class is from Apache Commons IO 2.4. Note the commons-io-2.4.jar file is required in the classpath to compile and run the examples. This library can be downloaded from the Apache Commons website.

The examples are tested on Windows operating system. The Apache Commons IO 2.4 API usage requires Java SE 6 or greater. Some examples in this article require Java SE 7.

1. File Name Components

This class defines six components within a filename. In an example file “X:\JCG\articles\org.apache.commons.io.FilenameUtils Example\notes.txt”:

  • X:\ – is the prefix
  • JCG\articles\org.apache.commons.io.FilenameUtils Example\ – is the path without the prefix
  • X:\JCG\articles\org.apache.commons.io.FilenameUtils Example\ – is the full path with the prefix
  • notes.txt – is the name
  • notes – is the base name
  • txt – is the extension

The following example shows how the components can be retrieved from a given filename using various methods of FilenameUtils class.

FilenameUtilsExample1.java

import org.apache.commons.io.FilenameUtils;

public class FilenameUtilsExample1 {

    public static void main(String [] args) {
			
        filenameComponents_();
    }

    private static void filenameComponents_() {
	
        String filename = "X:\\JCG\\articles\\org.apache.commons.io.FilenameUtils Example\\notes.txt";
	
        System.out.println("*** File name components ***");
        System.out.println("File name: " + filename);
	
        String prefix = FilenameUtils.getPrefix(filename);
        System.out.println("Prefix: " + prefix);
		
        String path = FilenameUtils.getPath(filename);
        System.out.println("Path: " + path);
		
        String fullPath = FilenameUtils.getFullPath(filename);
        System.out.println("Full path: " + fullPath);
		
        String name = FilenameUtils.getName(filename);
        System.out.println("Name: " + name);
		
        String baseName = FilenameUtils.getBaseName(filename);
        System.out.println("Base name: " + baseName);
		
        String extension = FilenameUtils.getExtension(filename);
        System.out.println("Extension: " + extension);
    }
}

The output:

*** File name components ***
File name: X:\JCG\articles\org.apache.commons.io.FilenameUtils Example\notes.txt
Prefix: X:\
Path: JCG\articles\org.apache.commons.io.FilenameUtils Example\
Full path: X:\JCG\articles\org.apache.commons.io.FilenameUtils Example\
Name: notes.txt
Base name: notes
Extension: txt

2. Path Normalization

Normalizing a file path is removing double (..) and single (.) dot path steps. The normalize() method is used for this. This method works on Windows as well as unix systems.

The following example shows normalizing a path with single and double dots:

FilenameUtilsExample1.java

import org.apache.commons.io.FilenameUtils;

public class FilenameUtilsExample1 {

    public static void main(String [] args) {
			
        normalize_();
    }

    private static void normalize_() {
	
        System.out.println("*** Normalization ***");

        String filename = "X:\\JCG\\.\\org.apache.commons.io.FilenameUtils Example\\notes.txt";
        System.out.println("Before: " + filename);
        String normalized = FilenameUtils.normalize(filename);
        System.out.println("After single dot normalization: " + normalized);
		
        filename = "X:\\JCG\\articles\\..\\notes.txt";
        System.out.println("Before: " + filename);
        normalized = FilenameUtils.normalize(filename);
        System.out.println("After double dot normalization: " + normalized);	
    }
}

The output:

*** Normalization ***
Before: X:\JCG\.\org.apache.commons.io.FilenameUtils Example\notes.txt
After single dot normalization: X:\JCG\org.apache.commons.io.FilenameUtils Example\notes.txt

Before: X:\JCG\articles\..\notes.txt
After double dot normalization: X:\JCG\notes.txt

From the output note that for the double dot (..) normalization, the double dot path segment and also the one segment before that are removed.

3. File Equality

The equals() method checks if two filename strings are same. This is a null safe method – the supplied filename can be a null and no exceptions are thrown.

A variation of this method is the equalsNormalized(). This method checks if two filename strings are same, after normalizing the filenames.

The following example shows the usage of the equals() method.

FilenameUtilsExample1.java

import org.apache.commons.io.FilenameUtils;

public class FilenameUtilsExample1 {

    public static void main(String [] args) {
			
        equals_();
    }

    private static void equals_() {
	
        System.out.println("*** File name equality ***");
	
        String filename1 = "FilenameUtilsExample.java";
        String filename2 = "FilenameUtilsExample.java";
        System.out.println("Filename 1: " + filename1);
        System.out.println("Filename 2: " + filename2);
        boolean result = FilenameUtils.equals(filename1, filename2);
        System.out.println("Equals: " + result);
		
        filename1 = null;
        System.out.println("Filename 1: " + filename1);
        System.out.println("Filename 2: " + filename2);
        result = FilenameUtils.equals(filename1, filename2);
        System.out.println("Equals: " + result);
    }
}

The output:

*** File name equality ***
Filename 1: FilenameUtilsExample.java
Filename 2: FilenameUtilsExample.java
Equals: true

Filename 1: null
Filename 2: FilenameUtilsExample.java
Equals: false

4. Concatenation

The concat() method concatenates a filename to a base path. For this method, the first argument is the base path, the second is the path to concatenate. The returned path is always normalized.

The following example shows the usage of the concat() method.

FilenameUtilsExample1.java

import org.apache.commons.io.FilenameUtils;

public class FilenameUtilsExample1 {

    public static void main(String [] args) {
			
        concat_();
    }

    private static void concat_() {
	
        System.out.println("*** Concatenation ***");
	
        // base and added names are paths
        String filename1 = "X:\\JCG\\Examples\\org.apache.commons.io.FilenameUtils";
        String filename2 = "articles\\";
        String concatenatedPath = FilenameUtils.concat(filename1, filename2);
        System.out.println("Filename 1: " + filename1 );
        System.out.println("Filename 2: " + filename2 );
        System.out.println("Concatenated: " + concatenatedPath);
		
        // base is path and added name is file name
        filename1 = "X:\\JCG\\Examples\\org.apache.commons.io.FilenameUtils";
        filename2 = "FilenameUtilsExample.java";
        concatenatedPath = FilenameUtils.concat(filename1, filename2);
        System.out.println("Filename 1: " + filename1 );
        System.out.println("Filename 2: " + filename2 );
        System.out.println("Concatenated: " + concatenatedPath);
		
        // base is reative path and added name is file name
        filename1 = "org.apache.commons.io.FilenameUtils";
        filename2 = "FilenameUtilsExample.java";
        concatenatedPath = FilenameUtils.concat(filename1, filename2);
        System.out.println("Filename 1: " + filename1 );
        System.out.println("Filename 2: " + filename2 );
        System.out.println("Concatenated: " + concatenatedPath);	
    }
}

The output:

*** Concatenation ***
Filename 1: X:\JCG\Examples\org.apache.commons.io.FilenameUtils
Filename 2: articles\
Concatenated: X:\JCG\Examples\org.apache.commons.io.FilenameUtils\articles\

Filename 1: X:\JCG\Examples\org.apache.commons.io.FilenameUtils
Filename 2: FilenameUtilsExample.java
Concatenated: X:\JCG\Examples\org.apache.commons.io.FilenameUtils\FilenameUtilsExample.java

Filename 1: org.apache.commons.io.FilenameUtils
Filename 2: FilenameUtilsExample.java
Concatenated: org.apache.commons.io.FilenameUtils\FilenameUtilsExample.java

5. Separator Conversion

This class defines methods to convert the path separator from unix (/) to Windows (\) and vice-versa.

The following example shows the usage of two methods separatorsToUnix() and separatorsToSystem(). There is also a method separatorsToWindows() to convert path separators to Windows system (\).

FilenameUtilsExample1.java

import org.apache.commons.io.FilenameUtils;

public class FilenameUtilsExample1 {

    public static void main(String [] args) {
			
        separators_();
    }

    private static void separators_() {
	
        System.out.println("*** Separator conversion ***");
	
        String filename = "X:\\JCG\\articles\\org.apache.commons.io.FilenameUtils Example\\notes.txt";
        System.out.println("File name: " + filename);
        filename = FilenameUtils.separatorsToUnix(filename);
        System.out.println("File name after separatorsToUnix(): " + filename);

        filename = "/JCG/articles/org.apache.commons.io.FilenameUtils Example/notes.txt";
        System.out.println("File name: " + filename);
        filename = FilenameUtils.separatorsToSystem(filename);
        System.out.println("File name after separatorsToSystem(): " + filename);
   }
}

The output:

*** Separator conversion ***
File name: X:\JCG\articles\org.apache.commons.io.FilenameUtils Example\notes.txt
File name after separatorsToUnix(): X:/JCG/articles/org.apache.commons.io.FilenameUtils Example/notes.txt

File name: /JCG/articles/org.apache.commons.io.FilenameUtils Example/notes.txt
File name after separatorsToSystem(): \JCG\articles\org.apache.commons.io.FilenameUtils Example\notes.txt

From the output:

  • File name: X:\JCG\articles\org.apache.commons.io.FilenameUtils Example\notes.txt
    File name after separatorsToUnix(): X:/JCG/articles/org.apache.commons.io.FilenameUtils Example/notes.txt
    The output shows the Windows path is converted to unix path.
  • File name: /JCG/articles/org.apache.commons.io.FilenameUtils Example/notes.txt
    File name after separatorsToSystem(): \JCG\articles\org.apache.commons.io.FilenameUtils Example\notes.txt
    The output shows the unix path is converted to Windows path; the program is run on a Windows system.

6. Directory Search

In this section the following two method’s usage is shown:

  • isExtension()
  • wildcardMatch()

The example has a directory and files with different names and extensions. The program searches for files with:

  • extensions java or class using the isExtension() method; for example FileChannelRead.java
  • matching wild card *Example?.txt; for example MyExample1.txt

The program iterates over a directory (note that a real directory with files is required) and uses the wild card and is extension methods for getting matched files. Note this example uses classes from java.nio.file package of Java SE 7 NIO2 File API.

FilenameUtilsExample2.java

import org.apache.commons.io.FilenameUtils;
import java.io.IOException;
import java.nio.file.Paths;
import java.nio.file.Path;
import java.nio.file.Files;
import java.nio.file.DirectoryStream;

public class FilenameUtilsExample2 {

    public static void main(String [] args)
            throws IOException {
			
        System.out.println("*** File extension and wildcard matching ***");
	
        String [] extensions = {"java", "class"};
        String wildcardMatcher = "*Example?.txt";
	
        Path dirPath = Paths.get("X:\\testdir\\");
        System.out.println("Directory being searched: " + dirPath.toString());
        DirectoryStream dirStream = Files.newDirectoryStream(dirPath);
		
        for (Path filePath : dirStream) {

            String filename = filePath.getFileName().toString();
            System.out.println(filename);
			
            // file extension matching
			
            boolean fileFound = FilenameUtils.isExtension(filename, extensions);
			
            if (fileFound) {
			
                System.out.println("    file with java or class extension");
            }
			
           // wild card matching

           fileFound = FilenameUtils.wildcardMatch(filename, wildcardMatcher);

           if (fileFound) {
			
               System.out.println("    file with *Example?.txt wild card match");
           }

        } // end for loop
		
        dirStream.close();
    }
}

The output:

*** File extension and wildcard matching ***
Directory being searched: X:\testdir
archives
commons-io-2.4.jar
FileChannelRead.class
    file with java or class extension
FileChannelRead.java
    file with java or class extension
FilenameUtilsExample.java
    file with java or class extension
FilenameUtilsExample1.txt
    file with *Example?.txt wild card match
FilenameUtilsExample1a.txt
FilenameUtilsExample2.txt
    file with *Example?.txt wild card match
notes.txt
readfile.txt
screenshots.docx
WatchEventExample.class
    file with java or class extension
WatchEventExample.java
    file with java or class extension

From the output:

  • Directory being searched: X:\testdir – This is the path of the directory being searched.
  • Note all files in the directory are listed. The files being searched are identified according to their matching. For example, FileChannelRead.class – file with java or class extension.

7. Download Java Source Code

This was an example of org.apache.commons.io.FilenameUtils

Download
You can download the full source code of this example here : FilenameUtilsExamples.zip

Prasad Saya

Prasad Saya is a software engineer with over ten years’ experience in application development, maintenance, testing and consulting on various platforms. He is a certified Java and Java EE developer. At present his interest is in developing Java applications. He also has experience working with databases and ERP applications.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button