取得檔案副檔名看似簡單,實則有許多邊界情況(如 abc.java.txt、無副檔名、隱藏檔)。本文提供三種解法並比較優缺點。
substring + lastIndexOf(標準做法)public static String getExtension(String fileName) {
int dot = fileName.lastIndexOf('.');
return (dot == -1 || dot == fileName.length() - 1) ? "" : fileName.substring(dot + 1);
}
FilenameUtils(推薦生產環境)// 依賴:commons-io
String ext = FilenameUtils.getExtension(fileName); // 自動處理邊界情況
Path API(現代化)public static String getExtensionModern(String fileName) {
Path path = Paths.get(fileName);
String name = path.getFileName().toString();
int dot = name.lastIndexOf('.');
return (dot == -1) ? "" : name.substring(dot + 1);
}
| 輸入 | 預期輸出 | 說明 |
|---|---|---|
| abc.txt | txt | 一般情況 |
| abc.java.txt | txt | 多重點號取最後一段 |
| .gitignore | gitignore | 隱藏檔 |
| README | "" | 無副檔名 |
| archive.tar.gz | gz | 雙重副檔名取最後 |
package com.itheima;
import java.io.File;
public class FileExtensionUtil {
public static String getExtension(File file) {
if (!file.isFile()) return "";
return getExtension(file.getName());
}
public static String getExtension(String fileName) {
int dot = fileName.lastIndexOf('.');
if (dot <= 0 || dot == fileName.length() - 1) return "";
return fileName.substring(dot + 1).toLowerCase();
}
}