上傳文件路徑可能來自 Windows (C:\path\file.txt) 或 Linux (/home/user/file.txt),需統一提取文件名。
String path = "/home/user/docs/report.pdf";
String fileName = path.substring(path.lastIndexOf('/') + 1); // 推薦:lastIndexOf 最快
// 或 split
String[] parts = path.split("/");
String fileName = parts[parts.length - 1];
public static String getFileName(String path) {
if (path == null) return null;
// 將所有反斜線統一為正斜線
String normalized = path.replace('\\', '/');
int idx = normalized.lastIndexOf('/');
return idx >= 0 ? normalized.substring(idx + 1) : normalized;
}
// 測試
System.out.println(getFileName("C:\\Users\\Tom\\file.txt")); // file.txt
System.out.println(getFileName("/var/log/app.log")); // app.log
System.out.println(getFileName("relative/path/file")); // file
System.out.println(getFileName("no_separator")); // no_separator
import java.nio.file.*;
public static String getFileNameNio(String path) {
return Paths.get(path).getFileName().toString();
}
// 注意:Windows 路徑在 Linux JVM 上可能解析異常,建議先 normalize
String safe = Paths.get(path.replace('\\', '/')).getFileName().toString();
// 同時匹配 / 和 \
String[] parts = path.split("[/\\\\]"); // 雙重轉義:字串 "\\" → 正則 "\" → 字面反斜線
String fileName = parts[parts.length - 1];
| 方法 | 耗時 (ns/op) | 備註 |
|---|---|---|
| lastIndexOf + substring | ~15 | 最快,無物件分配 |
| replace + lastIndexOf | ~30 | 跨平台通用 |
| Paths.get | ~120 | 物件創建多,功能豐富 |
| split 正則 | ~200 | 正則編譯開銷大 |
lastIndexOf('/') 後手動處理反斜線,或預先統一分隔符。Paths.get() / File API。Pattern.compile("[/\\\\]")。