在 iOS 中從完整文件路徑 (如 /Application/Mobile/Lib/123.abc) 提取文件名 (123.abc),最簡單的方法是使用 NSString 的 lastPathComponent 方法。
NSString *fullPath = @"/Application/Mobile/Lib/123.abc";
NSString *fileName = [fullPath lastPathComponent];
// 結果: @"123.abc"
| 方法 | 功能 | 示例輸入 | 輸出 |
|---|---|---|---|
| lastPathComponent | 獲取最後一級路徑 (文件名或目錄名) | /a/b/c.txt | c.txt |
| pathExtension | 獲取擴展名 | /a/b/c.txt | txt |
| deletingPathExtension | 移除擴展名 | /a/b/c.txt | /a/b/c |
| deletingLastPathComponent | 獲取父目錄路徑 | /a/b/c.txt | /a/b |
| appendingPathComponent: | 拼接路徑 | /a/b + "c.txt" | /a/b/c.txt |
NSString *path = @"/var/mobile/Documents/report_v2.1.pdf";
NSString *fileName = [path lastPathComponent]; // report_v2.1.pdf
NSString *extension = [path pathExtension]; // pdf
NSString *nameWithoutExt = [[path lastPathComponent] deletingPathExtension]; // report_v2.1
NSString *directory = [path deletingLastPathComponent]; // /var/mobile/Documents
NSURL *fileURL = [NSURL fileURLWithPath:path];
NSString *fileName = [fileURL lastPathComponent]; // 同樣結果
// 或使用 URLResourceValues (iOS 11+)
NSError *error = nil;
NSURLResourceValues *values = [fileURL resourceValuesForKeys:@[NSURLNameKey, NSURLTypeIdentifierKey] error:&error];
if (!error) {
NSString *name = values.name; // 文件名
NSString *uti = values.typeIdentifier; // 統一類型標識符
}
lastPathComponent 對目錄路徑也有效:@"/a/b/c/" 返回 @"c"NSURL/URL 類別,自動處理百分號編碼等
let path = "/Application/Mobile/Lib/123.abc"
let fileName = (path as NSString).lastPathComponent
// 或 Swift 原生
let url = URL(fileURLWithPath: path)
let fileName2 = url.lastPathComponent
let ext = url.pathExtension