IE 瀏覽器上傳檔案時會送出完整路徑(如 C:\Documents and Settings\user\My Documents\file.gif),需擷取純檔名 file.gif。
String fullPath = "C:/Documents and Settings/collin/My Documents/111-lazyloading.gif";
// Windows 路徑分隔符為 \,Java 字串需雙重跳脫 \\\\ 代表正則的 \\
String[] parts = fullPath.split("\\\\");
if (parts.length > 1) {
String fileName = parts[parts.length - 1];
System.out.println(fileName); // 111-lazyloading.gif
}
"\\\\" → 正則引擎看到 \\ → 匹配單一反斜線 \/ 則直接 split("/")String fullPath = "C:\\Documents\\Settings\\user\\file.gif"; // 或 Unix 路徑
// 1. 將所有反斜線統一為正斜線
// 2. 再以正斜線分割
String[] parts = fullPath.replaceAll("\\\\", "/").split("/");
if (parts.length > 1) {
String fileName = parts[parts.length - 1];
System.out.println(fileName); // file.gif
}
\ 與 Unix/Linux /import java.nio.file.Path;
import java.nio.file.Paths;
Path path = Paths.get(fullPath);
String fileName = path.getFileName().toString();
System.out.println(fileName); // 自動處理跨平台分隔符
| 方法 | 適用場景 | 效能 | 可讀性 |
|---|---|---|---|
| split("\\\\") | 純 Windows 路徑 | 高 | 中 |
| replaceAll + split | 跨平台、未知來源路徑 | 中 | 高 |
| Paths.get().getFileName() | Java 7+、標準路徑字串 | 高 | 最高 |
java.nio.file.Path APIreplaceAll("\\\\", "/").split("/") 跨平台最穩健File.separator 或 FileSystems.getDefault().getSeparator()