Java FilenameUtils-class And Method Code Example


Here's an example of how to use the FilenameUtils class from the org.apache.commons.io package in Java to work with file names:

import org.apache.commons.io.FilenameUtils;

public class Main {
    public static void main(String[] args) {
        String fullPath = "C:\\path\\to\\file.txt";
        String baseName = FilenameUtils.getBaseName(fullPath);
        String extension = FilenameUtils.getExtension(fullPath);
        String pathNoEndSeparator = FilenameUtils.getFullPathNoEndSeparator(fullPath);
        
        System.out.println("Base name: " + baseName);
        System.out.println("Extension: " + extension);
        System.out.println("Path without end separator: " + pathNoEndSeparator);
    }
}

This example shows how to use the FilenameUtils class to extract different parts of a file name. The getBaseName() method is used to extract the base name of the file (i.e. the name without the extension), the getExtension() method is used to extract the extension of the file, and the getFullPathNoEndSeparator() method is used to extract the path of the file without the end separator.

It's important to note that FilenameUtils class provides a wide range of utility methods to perform operations on file names, such as normalize, concatenate, and compare, and it also provides methods to work with different file name separators.