Apache Commons IO - FilenameUtils Class



Overview

FilenameUtils class provides methods 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 - Getting Path details using FilenameUtils Class

CommonsIoTester.java

package com.tutorialspoint;

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

public class CommonsIoTester {
   public static void main(String[] args) 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));
   }
}

Output

It will print the following result −

Full Path: C:\dev\project\
Relative Path: dev\project\
Prefix: C:\

Example - Getting File details using FilenameUtils Class

CommonsIoTester.java

package com.tutorialspoint;

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

public class CommonsIoTester {
   public static void main(String[] args) throws IOException {
      String path = "C:\\dev\\project\\file.txt";
      System.out.println("Extension: " + FilenameUtils.getExtension(path));
      System.out.println("Base: " + FilenameUtils.getBaseName(path));
      System.out.println("Name: " + FilenameUtils.getName(path));
   }
}

Output

It will print the following result −

Extension: txt
Base: file
Name: file.txt

Example - Getting Normalized Path using FilenameUtils Class

CommonsIoTester.java

package com.tutorialspoint;

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

public class CommonsIoTester {
   public static void main(String[] args) throws IOException {
      String filename = "C:/commons/io/../lang/project.xml";
      System.out.println("Normalized Path: " + FilenameUtils.normalize(filename));
   }
}

Output

It will print the following result −

Normalized Path: C:\commons\lang\project.xml
Advertisements