Apache Commons IO - FilenameUtils
提供在不使用文件对象的情况下使用文件名的方法。 它以类似的方式在不同的操作系统上工作。 此类解决了从基于 Windows 的开发机器迁移到基于 Unix 的生产机器时的问题。
类声明
以下是 org.apache.commons.io.FilenameUtils 类的声明 −
public class FilenameUtils extends Object
FilenameUtils 的特点
这个类在一个文件名中定义了六个组件。 将示例位置视为 C:\dev\project\file.txt。 那么组件是 −
- Prefix - C:\
- Relative Path - dev\project\
- Absolute path - C:\dev\project\
- Name - file.txt
- Base name - file
- Extension - txt
要识别目录,请在文件名中添加分隔符。
FilenameUtils 类示例
FilenameUtils 类的示例如下所示 −
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));
}
}
输出
它将打印以下结果。
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

