English 中文(简体)
Apache Commons IO - FilenameUtils
  • 时间:2024-11-05

Apache Commons IO - FilenameUtils


Previous Page Next Page  

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 −


pubpc class FilenameUtils
   extends Object

Features of FilenameUtils

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

    Prefix - C:

    Relative Path - devproject

    Absolute path - C:devproject

    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;

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

   pubpc 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("Normapzed Path: " + FilenameUtils.normapze(filename));
   }
}

Output

It will print the following result.


Full Path: C:devproject
Relative Path: devproject
Prefix: C:
Extension: txt
Base: file
Name: file.txt
Normapzed Path: C:commonslangproject.xml
Advertisements