Apache Commons IO - FilenameUtils



Provides method to work with file names without using File Object. It works on different operating systems in similar way. This class solves problems when moving from a Windows based development machine to a Unix based production machine.

Class Declaration

Following is the declaration for org.apache.commons.io.FilenameUtils Class −

public class FilenameUtils
   extends Object

Features of FilenameUtils

This class defines six components within a filename. Consider an example location as C:\dev\project\file.txt. Then the components are −

  • Prefix - C:\
  • Relative Path - dev\project\
  • Absolute path - C:\dev\project\
  • Name - file.txt
  • Base name - file
  • Extension - txt

To identify a directory, add a separator to file name.

Example of FilenameUtils Class

An example of FilenameUtils Class is given below −

IOTester.java

import java.io.IOException;
import org.apache.commons.io.FilenameUtils;

public class IOTester {
   public static void main(String[] args) {
      try {
         //Using FilenameUtils
         usingFilenameUtils();
      } catch(IOException e) {
         System.out.println(e.getMessage());
      }
   }

   public static void usingFilenameUtils() throws IOException {
      String path = "C:\\dev\\project\\file.txt";
      System.out.println("Full Path: " +FilenameUtils.getFullPath(path));
      System.out.println("Relative Path: " +FilenameUtils.getPath(path));
      System.out.println("Prefix: " +FilenameUtils.getPrefix(path));
      System.out.println("Extension: " + FilenameUtils.getExtension(path));
      System.out.println("Base: " + FilenameUtils.getBaseName(path));
      System.out.println("Name: " + FilenameUtils.getName(path));

      String filename = "C:/commons/io/../lang/project.xml";
      System.out.println("Normalized Path: " + FilenameUtils.normalize(filename));
   }
}

Output

It will print the following result.

Full Path: C:\dev\project\
Relative Path: dev\project\
Prefix: C:\
Extension: txt
Base: file
Name: file.txt
Normalized Path: C:\commons\lang\project.xml
Advertisements