建議大家看 JKSwiftExtension,測試用例在 FileManagerExtensionViewController ,是關(guān)于沙盒的操作
在iOS開發(fā)我們會遇到文件、音頻、視頻等等下載后本地存儲的情況,這時對讀文件,寫文件就顯得很重要,對文件夾以及文件中的文件的操作,這時就可以使用NSFileManager(FileManager)或NSFileHandle(FileHandle)來實現(xiàn)。下面會用OC和Swift的對比來實現(xiàn)對文件和文件夾的操作
- 文件管理器(NSFileManager/FileManager):此類主要是對文件進行的操作(創(chuàng)建/刪除/改名等)以及文件信息的獲取。
- 文件連接器(NSFileHandle/FileHandle):此類主要是對文件內(nèi)容進行讀取和寫入操作。
一、沙盒以及組成部分
iOS應(yīng)用程序只能對自己創(chuàng)建的文件系統(tǒng)讀取文件,這個"獨立","封閉","安全"的空間,稱之為沙盒。
- 1.1、Home目錄(應(yīng)用程序包)
- 整個應(yīng)用程序各文檔所在的目錄,包含了所有的資源文件和可執(zhí)行文件
- 1.2、Documents
- 保存應(yīng)用運行時生成的需要持久化的數(shù)據(jù),iTunes同步設(shè)備時會備份該目錄
- 需要保存由"應(yīng)用程序本身"產(chǎn)生的文件或者數(shù)據(jù),例如: 游戲進度,涂鴉軟件的繪圖
- 目錄中的文件會被自動保存在 iCloud
- 注意: 不要保存從網(wǎng)絡(luò)上下載的文件,否則會無法上架!
- 1.3、tmp
- 保存應(yīng)用運行時所需要的臨時數(shù)據(jù)或文件,"后續(xù)不需要使用",使用完畢后再將相應(yīng)的文件從該目錄刪除。
- 應(yīng)用沒有運行,系統(tǒng)也可能會清除該目錄下的文件
- iTunes不會同步備份該目錄
- 重新啟動手機, tmp 目錄會被清空
- 系統(tǒng)磁盤空間不足時,系統(tǒng)也會自動清理
- 1.4、Library/Cache
- 保存應(yīng)用運行時生成的需要持久化的數(shù)據(jù),iTunes同步設(shè)備時不備份該目錄。一般存放體積大、不需要備份的非重要數(shù)據(jù)
- 保存臨時文件,"后續(xù)需要使用",例如: 緩存的圖片,離線數(shù)據(jù)(地圖數(shù)據(jù))
- 系統(tǒng)不會清理 cache 目錄中的文件
- 就要求程序開發(fā)時, "必須提供 cache 目錄的清理解決方案"
- 1.5、Library/Preference
- 保存應(yīng)用的所有偏好設(shè)置,IOS的Settings應(yīng)用會在該目錄中查找應(yīng)用的設(shè)置信息。iTunes
- 用戶偏好,使用 NSUserDefault 直接讀寫!
- 如果想要數(shù)據(jù)及時寫入硬盤,還需要調(diào)用一個同步方法 synchronize()
- 1.6.程序.app,與另三個路徑的父路徑不同
- 這是應(yīng)用程序的程序包目錄,包含應(yīng)用程序的本身。由于應(yīng)用程序必須經(jīng)過簽名,所以您在運行時不能對這個目錄中的內(nèi)容進行修改,否則可能會使應(yīng)用程序無法啟動
二、對文件以及文件夾的操作
2.1、獲取各個目錄的路徑
-
2.1.1、HomeDirectory
OC: NSString *filePath = NSHomeDirectory(); Swift: let homePath = NSHomeDirectory()
-
2.1.2、Documents
OC: 方法一 NSString * documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0]; 方法二 NSString * documentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]; Swift: 方法1 let documentsPaths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true) let documentsPath = documentPaths[0] 方法2 let documentsPath = NSHomeDirectory()+"/Documents"
-
2.1.3、Caches
OC: 方法一 NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0]; 方法二 NSString *cachesPath= [NSHomeDirectory() stringByAppendingPathComponent:@"/Library/Caches"]; Swift: 方法1 let cachePaths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true) let cachePath = cachePaths.last 方法2 let cachePath = NSHomeDirectory()+"/Library/Caches"
-
2.1.4、Library
OC: 方法一 NSString * libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0]; 方法二 NSString * libraryPath = [NSHomeDirectory() stringByAppendingPathComponent:@"/Library"]; Swift: 方法1 let libraryPaths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.libraryDirectory, FileManager.SearchPathDomainMask.userDomainMask, true) let libraryPath = libraryPaths[0] 方法2 let libraryPath = NSHomeDirectory()+"/Library"
-
2.1.5、tmp
OC: 方法一 NSString *tempPath = NSTemporaryDirectory(); 方法二 NSString * tempPath = [NSHomeDirectory() stringByAppendingPathComponent:@"/tmp"]; Swift: 方法1 let tempPath = NSTemporaryDirectory() 方法2 let tempPath = NSHomeDirectory()+"/tmp"
2.2、根據(jù)傳件來的路徑創(chuàng)建文件夾 創(chuàng)建文件目錄(藍色的,文件夾和文件是不一樣的)
應(yīng)用程序目錄, Caches、Library、Documents目錄文件夾下創(chuàng)建文件夾(藍色的)
下面以Documents為例創(chuàng)建JKFile為例
-
OC
NSString *filePath=[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/JKFile"]; - (NSString *)jKCreateDir:folderName{ NSString *filePath=[NSHomeDirectory() stringByAppendingPathComponent: folderName]; NSFileManager *fileManager = [NSFileManager defaultManager]; BOOL isDir = NO; // fileExistsAtPath 判斷一個文件或目錄是否有效,isDirectory判斷是否一個目錄 BOOL existed = [fileManager fileExistsAtPath:filePath isDirectory:&isDir]; if ( !(isDir == YES && existed == YES) ) { // 不存在的路徑才會創(chuàng)建 [fileManager createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil]; } return filePath; }
-
Swift:
let jKFilePath = NSHomeDirectory() + "/Documents/JKFile"; func jKCreateFolder(folderName: NSString) -> NSString { let fileManager: FileManager = FileManager.default let filePath = "\(folderName)" let exist = fileManager.fileExists(atPath: filePath) // 不存在的路徑才會創(chuàng)建 if (!exist) { //withIntermediateDirectories為ture表示路徑中間如果有不存在的文件夾都會創(chuàng)建 try! fileManager.createDirectory(atPath: filePath,withIntermediateDirectories: true, attributes: nil) } return filePath as NSString }
2.3、刪除文件夾(先判斷文件夾存不存在)
-
OC
NSString *filePath=[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/JKFile"]; - (void)jKRemovefolder:(NSString *)filePathName { // filePath: 文件/目錄的路徑 NSFileManager *fileManager = [NSFileManager defaultManager]; NSString *filePath = [NSString stringWithFormat:@"%@",filePathName]; BOOL isDir = NO; // fileExistsAtPath 判斷一個文件或目錄是否有效,isDirectory判斷是否一個目錄 BOOL existed = [fileManager fileExistsAtPath:filePath isDirectory:&isDir]; if ( !(isDir == YES && existed == YES) ) { // 不存在的路徑才會創(chuàng)建 return; } //文件夾 [fileManager removeItemAtPath:filePath error:nil]; }
-
Swift:
let jKFilePath = NSHomeDirectory() + "/Documents/JKFile"; func jKRemovefolder(folderName: NSString){ let fileManager: FileManager = FileManager.default let filePath = "\(folderName)" let exist = fileManager.fileExists(atPath: filePath) // 查看文件夾是否存在,如果存在就直接讀取,不存在就直接反空 if (exist) { try! fileManager.removeItem(atPath: filePath) }else{ // 不存在就不做什么操作了 } }
2.4、刪除文件
-
OC
- (void)jKRemovefile:(NSString *)filePathName { // filePath: 文件/目錄的路徑 NSFileManager *fileManager = [NSFileManager defaultManager]; NSString *filePath = [NSString stringWithFormat:@"%@",filePathName]; //移除文件 [fileManager removeItemAtPath:filePath error:nil]; }
-
Swift:
func jKRemovefile(folderName: NSString){ let fileManager: FileManager = FileManager.default let filePath = "\(folderName)" //移除文件 try! fileManager.removeItem(atPath: filePath) }
2.5、深度遍歷(搜索文件夾)
-
2.5.1、深度搜索遍歷一(subpathsAtPath)深度遍歷,會遞歸遍歷子文件夾(包括符號鏈接,所以要求性能的話用enumeratorAtPath)
獲取某個文件下的所有文件的名字-
OC
NSString *filePath = NSHomeDirectory(); -(NSArray *)jKGetAllFileNames:(NSString *)folderName { NSFileManager *fileManager = [NSFileManager defaultManager]; // 取得一個目錄下得所有文件名 NSArray *files = [fileManager subpathsAtPath:[self jKCreateFolder:folderName]]; //NSLog(@"pdf名字的數(shù)量=%ld 數(shù)組=%@",files.count,files); return files; }
-
-
Swift:
let jKFilePath = NSHomeDirectory(); func jKGetAllFileNames(folderName: NSString) -> NSArray{ let filePath = "\(folderName)" let exist = fileManager.fileExists(atPath: filePath) // 查看文件夾是否存在,如果存在就直接讀取,不存在就直接反空 if (exist) { let subPaths = fileManager.subpaths(atPath: folderName as String) return subPaths! as NSArray }else{ return [] } }
-
2.5.2、深度遍歷二,會遞歸遍歷子文件夾(但不會遞歸符號鏈接)
-
OC
// folderNmae:文件夾的名字 -(NSArray *)jKDeepSearchEnumeratorAllFileNames:(NSString *)folderName{ NSFileManager *fileManager = [NSFileManager defaultManager]; // 取得一個目錄下得所有文件名 NSDirectoryEnumerator *files = [fileManager enumeratorAtPath:[self jKCreateFolder:folderName]]; //NSLog(@"pdf名字的數(shù)量=%ld 數(shù)組=%@",files.count,files); return files.allObjects; }
-
Swift:
func jKDeepSearchAllFiles(folderName: NSString) -> NSArray { let filePath = "\(folderName)" let exist = fileManager.fileExists(atPath: filePath) // 查看文件夾是否存在,如果存在就直接讀取,不存在就直接反空 if (exist) { let contentsOfPathArray = fileManager.enumerator(atPath: filePath) return contentsOfPathArray!.allObjects as NSArray }else{ return [] } }
-
2.6、對指定路徑執(zhí)行淺搜索,返回指定目錄路徑下的文件、子目錄及符號鏈接的列表(只尋找一層)
-
OC
/**對指定路徑執(zhí)行淺搜索,返回指定目錄路徑下的文件、子目錄及符號鏈接的列表(只尋找一層)*/ NSString *customPath = [NSString stringWithFormat:@"%@",[JKFilePathOperationExtension jKHomeDirectory]]; -(NSArray *)jKShallowSearchAllFiles:(NSString *)filePath{ NSFileManager *fileManager = [NSFileManager defaultManager]; NSArray *contentsOfPathArray = [fileManager contentsOfDirectoryAtPath:filePath error:nil]; return contentsOfPathArray; }
-
Swift:
/** 對指定路徑執(zhí)行淺搜索,讀取指定目錄路徑下的文件、子目錄及符號鏈接的列表(只尋找一層)*/ let jKFilePath = NSHomeDirectory() func jKShallowSearchAllFiles(folderName: NSString) -> NSArray { let filePath = "\(folderName)" let contentsOfPathArray = try! fileManager.contentsOfDirectory(atPath: filePath); return contentsOfPathArray as NSArray }
2.7、判斷文件或文件夾是否存在
-
OC
+(BOOL)jkJudgeFileOrFolderExists:(NSString *)filePathName{ NSFileManager *fileManager = [NSFileManager defaultManager]; NSString *filePath = [NSString stringWithFormat:@"%@",filePathName]; BOOL isDir = NO; // fileExistsAtPath 判斷一個文件或目錄是否有效,isDirectory判斷是否一個目錄 BOOL existed = [fileManager fileExistsAtPath:filePath isDirectory:&isDir]; if ( !(isDir == YES && existed == YES) ) { // 不存在的路徑 return NO; }else{ return YES; } return nil; }
-
Swift:
func jkJudgeFileOrFolderExists(folderName: NSString) -> Bool { let filePath = "\(folderName)" let exist = fileManager.fileExists(atPath: filePath) // 查看文件夾是否存在,如果存在就直接讀取,不存在就直接反空 if (exist) { return true }else{ return false } }
2.8、創(chuàng)建文件(如:動畫樂園.text格式的文本文件)
-
OC
/**folderNmae:文件的名字*/ - (NSString *)jKCreateFile:(NSString *)folderName{ NSString *filePath = [NSString stringWithFormat:@"%@",folderName]; NSFileManager *fileManager = [NSFileManager defaultManager]; BOOL isDir = NO; // fileExistsAtPath 判斷一個文件或目錄是否有效,isDirectory判斷是否一個目錄 BOOL existed = [fileManager fileExistsAtPath:filePath isDirectory:&isDir]; if ( !(isDir == YES && existed == YES) ) { // 不存在的路徑才會創(chuàng)建 [fileManager createFileAtPath:filePath contents:nil attributes:nil]; } return filePath; }
-
Swift:
// fileName:文件的名字(不是文件夾) // baseFilePath: 文件的基礎(chǔ)路徑 // content: 存進文件的內(nèi)容 /** 根據(jù)傳件來的路徑創(chuàng)建文件*/ func jKCreateFile(fileName: NSString,baseFilePath: NSString) -> (filePath: NSString,createStatus: Bool) { // NSHomeDirectory():應(yīng)用程序目錄 let filePath = "\(baseFilePath)" + "/\(fileName)" let exist = fileManager.fileExists(atPath: filePath) // 不存在的文件路徑才會創(chuàng)建 if (!exist) { //withIntermediateDirectories為ture表示路徑中間如果有不存在的文件夾都會創(chuàng)建 let createSuccess = fileManager.createFile(atPath: filePath,contents:nil,attributes:nil) return (filePath as NSString,createSuccess as Bool) } return (filePath as NSString,true) }
2.9、可以通過write(to:)方法,可以創(chuàng)建文件并將對象(文件,音頻,圖片,視頻以及數(shù)組,字典)都可以寫入文件
簡單對象:iOS中提供四種類型可以直接進行文件存取:NSString(字符串)、NSArray(數(shù)組)、NSDictionary(字典)、NSData(數(shù)據(jù))(以上類型包括子類)
注意:數(shù)組(可變與不可變)和字典(可變與不可變)中元素對象的類型,也必須是上述四種,否則不能直接寫入文件
-
2.9.1、把NSSString保存到上面“動畫樂園.text”的文件里面
NSSString保存到上面“動畫樂園.text”的文件里面-
OC
// 文件的路徑(以文件存在為基礎(chǔ),創(chuàng)建文件請看2.9) NSString * path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/動畫樂園.text"]; NSString *content = @"動畫樂園歡迎你" // 內(nèi)容寫入 [content writeToFile: path atomically:YES encoding:NSUTF8StringEncoding error:nil];
-
Swift:
let path = NSHomeDirectory() + "/Documents/動畫樂園.text" let info = "動畫樂園歡迎你" as String try! info.write(toFile: path, atomically: true, encoding: String.Encoding.utf8)
-
-
2.9.2、把本地圖片或者網(wǎng)絡(luò)圖片保存到上面“圖片”的文件夾里面
filePath圖片的路徑是提前存在的(沒有的話看上面的去創(chuàng)建文件夾)
把本地圖片或者網(wǎng)絡(luò)圖片保存到上面**“圖片”**的文件夾里面-
OC
// 本地圖片的名字 NSString *imageString = @"testimage.png"; UIImage *image = [UIImage imageNamed:imageString]; NSData *data = UIImagePNGRepresentation(image); // 圖片的存儲文件夾 NSString *customPath = [NSString stringWithFormat:@"%@%@",NSHomeDirectory(),@"/Documents/圖片"]; // 圖片的存儲路徑 imagePath = [NSString stringWithFormat:@"%@/%@", customPath, imageString]; [data writeToFile: imagePath atomically:YES]; 網(wǎng)絡(luò)圖片 NSString *imageStr = @"http://images.ciotimes.com/o_1can10mm91sd91c6n1thv15oel8g9.png"; NSString *customPath = [NSString stringWithFormat:@"%@/%@",[JKFilePathOperationExtension jKDocuments],@"jk.png"]; NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageStr]]; //轉(zhuǎn)換為圖片保存到以上的沙盒路徑中 UIImage * currentImage = [UIImage imageWithData:data]; //其中參數(shù)0.5表示壓縮比例,1表示不壓縮,數(shù)值越小壓縮比例越大 [UIImageJPEGRepresentation(currentImage, 0.5) writeToFile:customPath atomically:YES];
-
Swift:
let filePath = NSHomeDirectory() + "/Documents/圖片/testimage.png" let image = UIImage(named: "testimage.png") let data:Data = UIImagePNGRepresentation(image!)! try? data.write(to: URL(fileURLWithPath: filePath))
-
-
2.9.3、把本數(shù)組寫到文件里面(array.plist的文件是已經(jīng)存在的基礎(chǔ)上)
把本數(shù)組寫到文件里面(array.plist的文件是已經(jīng)存在的基礎(chǔ)上)-
OC
// 創(chuàng)建數(shù)組 NSArray *array = @[@"1",@"2",@"3"]; // 文件路徑(前提是已經(jīng)存在),創(chuàng)建文件請看上面2.9 NSString *customPath = [NSString stringWithFormat:@"%@%@",NSHomeDirectory(),@"/Documents/array.plist"]; [array writeToFile:filePath atomically:YES];
-
Swift
let filePath = NSHomeDirectory() + "/Documents/array.plist" let array = NSArray(objects: "我","??","你") array.write(toFile: filePath, atomically: true)
-
-
2.9.4、把本字典寫到文件里面(dictionary.plist的文件是已經(jīng)存在的基礎(chǔ)上)
把本字典寫到文件里面(dictionary.plist的文件是已經(jīng)存在的基礎(chǔ)上)-
OC
NSString *customPath = [NSString stringWithFormat:@"%@%@",NSHomeDirectory(),@"/Documents/dictionary.plist"]; // 創(chuàng)建字典 NSDictionary *dict = @{@"1":@"9",@"2":@"8",@"3":@"7",@"4":@"6"}; dict.write(toFile: filePath, atomically: true)
-
Swift
let filePath = NSHomeDirectory() + "/Documents/dictionary.plist" let dictionary = NSDictionary(dictionary: ["name":"JK","age":"26"]) dictionary.write(toFile: filePath, atomically: true)
-
2.10、復制文件
-
OC
NSString *fromPath = [NSString stringWithFormat:@"%@%@",NSHomeDirectory(),@"/Documents/我的筆記.text"]; NSString *toPath = [NSString stringWithFormat:@"%@%@",NSHomeDirectory(),@"/Documents/復制后的筆記.text"]; NSFileManager *fileManager = [NSFileManager defaultManager]; BOOL isCopySuccess = [fileManager copyItemAtPath: fromPath toPath: toPath error:nil];
-
Swift
let homeDirectory = NSHomeDirectory() let fomePath = homeDirectory + "/Documents/我的筆記.text" let toPath = homeDirectory + "/Documents/復制后的筆記.text" let fileManager1 = FileManager.default try! fileManager1.copyItem(atPath: fomePath as String, toPath: toPath as String)
2.11、移動文件或者文件夾
文件夾或者文件,這里是文件夾JKPdf要提前建好,創(chuàng)建方式看上面
-
OC
NSString *fromPath = [NSString stringWithFormat:@"%@%@",NSHomeDirectory(),@"/Documents/JKPdf"]; NSString *toPath = [NSString stringWithFormat:@"%@%@",NSHomeDirectory(),@"/tmp/JKPdf"]; NSFileManager *fileManager = [NSFileManager defaultManager]; BOOL isMoveSuccess = [fileManager moveItemAtPath:fromPath toPath:toPath error:nil];
-
Swift
let fomePath =NSHomeDirectory() + "/Documents/JKPdf" let toPath = NSHomeDirectory() + "/tmp/JKPdf" let fileManagerMove = FileManager.default try! fileManagerMove.moveItem(atPath: fromUrl as String, toPath: toUrl as String)
2.12、讀取文件
-
2.12.1、文件的類型為文本,如 我的筆記.text
-
OC
// 拿到我的筆記.text的路徑 NSString *customPath = @"路徑"; // 取出文本的內(nèi)容 NSString *str = [NSString stringWithContentsOfFile:customPath encoding:NSUTF8StringEncoding error:nil];
-
Swift
let path = NSHomeDirectory() + "/Documents/我的筆記.text" let readHandler = FileHandle(forReadingAtPath: path) let data = readHandler?.readDataToEndOfFile() let readString = String(data: data!, encoding: String.Encoding.utf8) print("文件內(nèi)容: \(String(describing: readString))")
-
-
2.12.2、讀取沙盒圖片
模仿SDWebImage: 加載圖片前先去沙盒尋找,如果有就加載沙盒里的圖片,沒有的話就加載網(wǎng)絡(luò)的圖片-
OC
/** 讀出圖片 imageUrl: 圖片的鏈接*/ +(void)jKReadImageWithImageUrl:(NSString *)imageUrl withReadImage:(ReadImage)readImage{ NSString *catchsImageStr = [imageUrl lastPathComponent]; NSFileManager *fileManager = [NSFileManager defaultManager]; NSString *filePath = [NSString stringWithFormat:@"%@/Library/Caches/JKImage/%@",NSHomeDirectory(),catchsImageStr]; // fileExistsAtPath 判斷一個文件或目錄是否有效 BOOL existed = [fileManager fileExistsAtPath:filePath]; if ( !(existed == YES) ) { // 圖片不存在沙盒里,檢查文件夾是否存在 NSString *folderPath = [NSString stringWithFormat:@"%@/Library/Caches/JKImage",NSHomeDirectory()]; BOOL isDir = NO; // fileExistsAtPath 判斷一個文件或目錄是否有效,isDirectory判斷是否一個目錄 BOOL existedFolder = [fileManager fileExistsAtPath:folderPath isDirectory:&isDir]; if ( !(isDir == YES && existedFolder == YES) ) { // 不存在的文件夾JKImage才會創(chuàng)建 [fileManager createDirectoryAtPath:folderPath withIntermediateDirectories:YES attributes:nil error:nil]; } // 文件夾存在就把圖片緩存進去 // 圖片不存在 NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrl]]; //轉(zhuǎn)換為圖片保存到以上的沙盒路徑中 UIImage * currentImage = [UIImage imageWithData:data]; //其中參數(shù)0.5表示壓縮比例,1表示不壓縮,數(shù)值越小壓縮比例越大 [UIImageJPEGRepresentation(currentImage, 0.5) writeToFile:[NSString stringWithFormat:@"%@/%@",folderPath,catchsImageStr] atomically:YES]; readImage(currentImage,YES); }else{ // 圖片在沙盒里直接取出 NSData *data = [NSData dataWithContentsOfFile:filePath]; UIImage *image = [UIImage imageWithData:data]; readImage(image,YES); } }
-
Swift
let path = NSHomeDirectory() + "/Documents/2.png" let fileManagerReadImage = FileManager.default let exist = fileManagerReadImage.fileExists(atPath: path) // 不存在直接返回false if (!exist) { print("存在圖片") }else{ let readHandler = FileHandle(forReadingAtPath: path) let data = (readHandler?.readDataToEndOfFile())! let image = UIImage(data: data) print("不存在圖片") }
-
2.13、獲取文件屬性(創(chuàng)建時間,修改時間,文件大小,文件類型等信息)
-
OC
let docPath = NSHomeDirectory() + "/Documents/我的筆記.text" NSFileManager *fileManager = [NSFileManager defaultManager]; NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:path error:nil]; if (fileAttributes != nil) { NSNumber *fileSize; NSString *fileOwner, *creationDate; NSDate *fileModDate; //NSString *NSFileCreationDate //文件大小 if ((fileSize = [fileAttributes objectForKey:NSFileSize])) { NSLog(@"文件的大小= %qi\n", [fileSize unsignedLongLongValue]); } //文件創(chuàng)建日期 if ((creationDate = [fileAttributes objectForKey:NSFileCreationDate])) { NSLog(@"文件創(chuàng)建的日期: %@\n", creationDate); } //文件所有者 if ((fileOwner = [fileAttributes objectForKey:NSFileOwnerAccountName])) { NSLog(@"Owner: %@\n", fileOwner); } //文件修改日期 if ((fileModDate = [fileAttributes objectForKey:NSFileModificationDate])) { NSLog(@"文件修改的日期: %@\n", fileModDate); } }else { NSLog(@"該文件不存在"); }
-
Swift
// 我的筆記.text文本是存在Documents下面的 let path = NSHomeDirectory() + "/Documents/我的筆記.text" let managerGetFile = FileManager.default let attributes = try? managerGetFile.attributesOfItem(atPath: path) //結(jié)果為Dictionary類型 print("創(chuàng)建時間:\(attributes[FileAttributeKey.creationDate]!)") print("修改時間:\(attributes[FileAttributeKey.modificationDate]!)") print("文件大小:\(attributes[FileAttributeKey.size]!)")
2.14、計算單個或多個文件夾的大小(清理數(shù)據(jù)常用)
-
OC
/** 計算文件夾的大小 folderPath: 文件夾的大小*/ -(NSString *)jKCalculateTheSizeOfTheFolderPath:(NSString *)folderPath{ NSFileManager *fileManager = [NSFileManager defaultManager]; BOOL isExist = [fileManager fileExistsAtPath:folderPath]; if (isExist) { unsigned long long folderSize = 0; NSArray *childerFiles=[fileManager subpathsAtPath:folderPath]; if (childerFiles.count != 0) { for (NSString *fileName in childerFiles) { NSString *fileAbsolutePath=[folderPath stringByAppendingPathComponent:fileName]; folderSize +=[self jKCalculateTheSizeOfTheFilePath:fileAbsolutePath]; } }else{ folderSize = [self jKCalculateTheSizeOfTheFilePath:folderPath]; } NSString *sizeString; if (folderSize >= 1024.0 * 1024.0) { sizeString = [NSString stringWithFormat:@"%.2fMB",folderSize / (1024.0 * 1024.0)]; }else if (folderSize >= 1024.0){ sizeString = [NSString stringWithFormat:@"%.fkb",folderSize / (1024.0)]; }else{ sizeString = [NSString stringWithFormat:@"%llub",folderSize]; } // unsigned long long return sizeString; } else { NSLog(@"file is not exist"); return @"0MB"; } } /** 計算文件的大小*/ -(unsigned long long)jKCalculateTheSizeOfTheFilePath:(NSString *)filePath{ NSFileManager *fileManager = [NSFileManager defaultManager]; BOOL isExist = [fileManager fileExistsAtPath:filePath]; if (isExist) { unsigned long long fileSize = [[fileManager attributesOfItemAtPath:filePath error:nil] fileSize]; return fileSize; } else { NSLog(@"file is not exist"); return 0; } }
-
Swift
/** 計算文件夾或者文件的大小 */ class func getSize(folderPath: String)-> String { if folderPath.count == 0 { return "0MB" as String } let manager = FileManager.default if !manager.fileExists(atPath: folderPath){ return "0MB" as String } var fileSize:Float = 0.0 do { let files = try manager.contentsOfDirectory(atPath: folderPath) for file in files { let path = folderPath + "/\(file)" fileSize = fileSize + fileSizeAtPath(filePath: path) } }catch{ fileSize = fileSize + fileSizeAtPath(filePath: folderPath) } print("大小==\(fileSize)") var resultSize = "" if fileSize >= 1024.0*1024.0{ resultSize = NSString(format: "%.2fMB", fileSize/(1024.0 * 1024.0)) as String }else if fileSize >= 1024.0{ resultSize = NSString(format: "%.fkb", fileSize/(1024.0 )) as String }else{ resultSize = NSString(format: "%llub", fileSize) as String } return resultSize } /** 計算單個文件或文件夾的大小 */ class func fileSizeAtPath(filePath:String) -> Float { let manager = FileManager.default var fileSize:Float = 0.0 if manager.fileExists(atPath: filePath) { do { let attributes = try manager.attributesOfItem(atPath: filePath) if attributes.count != 0 { fileSize = attributes[FileAttributeKey.size]! as! Float } }catch{ } } return fileSize; }
最后給大家提供上面封裝的demo
JKSwiftFileOperation與JKOCFilePathOperation
請給個喜歡,謝謝!我們的iOS開發(fā)交流QQ群:584599353