Commons Io 简明教程

Apache Commons IO - FilenameUtils

提供一种方法来使用文件名而不使用 File Object 来工作。它以类似的方式在不同的操作系统上工作。此类解决从基于 Windows 的开发机器移至基于 Unix 的生产机器时的问题。

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

以下是 org.apache.commons.io.FilenameUtils 类的声明 -

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

public class FilenameUtils
   extends Object

Features of FilenameUtils

此类定义文件名中的六个组件。考虑一个示例位置为 C:\dev\project\file.txt 。那么这些组件就是 -

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

  1. Prefix - C:\

  2. Relative Path - dev\project\

  3. Absolute path - C:\dev\project\

  4. Name - file.txt

  5. Base name - file

  6. Extension - txt

要识别目录,请向文件名添加分隔符。

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

Example of FilenameUtils Class

下面给出了 FilenameUtils 类的示例 -

An example of FilenameUtils Class is given below −

IOTester.java

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