NSFileManager:
沙盒根目錄有3個文件夾:
1.Documents
建議程序建立產生的文件以及應用瀏覽產生的文件數據保存在該目錄下
iTunes備份與恢復時會包括此目錄
2.Library
存儲程序的默認設置或其它狀態信息
1.Caches
存放緩存文件,保存持久化數據
不被iTunes同步
通常存放一些比較大的文件而又不須要備份的文件
2.Preferences
3.tmp
存放臨時文件,不持久化
獲取沙盒跟路徑:
NSString *homePath=NSHomeDirectory();
獲取Documents目錄路徑:
NSString *docPath=[NSSearchPathForDirectoriesInDomains((NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];數組
獲取Cache目錄路徑:
NSString *docPath=[NSSearchPathForDirectoriesInDomains((NSCachesDirectory, NSUserDomainMask, YES)objectAtIndex:0];緩存
獲取Tmp目錄路徑:
NSString *tmpPath=NSTemporaryDirectory();app
建立文件夾:
NSFileManager *fileManager=[NSFileManager defaultManager];
NSString *docPath=[NSSearchPathForDirectoriesInDomains((NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSString *myDirPath=[docPath stringByAppendingPathComponent:@"myDir"];
BOOL result=[fileManager createDirectoryAtPath:myDirPath withIntermediateDirectories:YES attributes:nil error:nil];
if(result){
NSLog(@"文件夾建立成功");
}else{
NSLog(@"文件夾建立失敗");
}工具
建立文件:
NSFileManager *fileManager=[NSFileManager defaultManager];
NSString *docPath=[NSSearchPathForDirectoriesInDomains((NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSString *myDirPath=[docPath stringByAppendingPathComponent:@"myDir"];
NSString *myFilePath=[myDirPath stringByAppendingPathComponent:@"myFile.txt"];
BOOL result=[fileManager createFileAtPath:myFilePath contents:nil attributes:nil];
if(result){
NSLog(@"文件建立成功");
}else{
NSLog(@"文件建立失敗");
}測試
寫數據到文件:
NSString *docPath=[NSSearchPathForDirectoriesInDomains((NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSString *myDirPath=[docPath stringByAppendingPathComponent:@"myDir"];
//字符串寫入
NSString *myFilePath=[myDirPath stringByAppendingPathComponent:@"myFile.txt"];
NSString *content=@"測試寫入內容";
BOOL result=[content writeToFile:myFilePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
/*數組寫入(若元素爲自定義類型對象則需實現歸檔協議,不然寫入失敗)
NSString *myFilePath=[myDirPath stringByAppendingPathComponent:@"myFile.txt"];
NSArray *content=@[@"a",@"b",@"c"];
BOOL result=[content writeToFile:myFilePath atomically:YES];
*/
/*字典寫入(若元素爲自定義類型對象則需實現歸檔協議,不然寫入失敗)
NSString *myFilePath=[myDirPath stringByAppendingPathComponent:@"myFile.plist"];
NSDictionary *content=@{@"key1":@"value1",@"key2",@"value2"};
BOOL result=[content writeToFile:myFilePath atomically:YES];
*/
/*混合數據寫入
NSString *myFilePath=[myDirPath stringByAppendingPathComponent:@"myFile.txt"];
NSString *temp = @"nihao 世界";
int dataInt = 1234;
float dataFloat = 3.14f;
NSMutableData *writer = [[NSMutableData alloc] init];
[writer appendData:[temp dataUsingEncoding:NSUTF8StringEncoding]];
[writer appendBytes:&dataInt length:sizeof(dataInt)];
[writer appendBytes:&dataFloat length:sizeof(dataFloat)];
[writer writeToFile:myFilePath atomically:YES];
*/
if(result){
NSLog(@"數據寫入成功");
}else{
NSLog(@"數據寫入失敗");
}
讀文件數據:
NSString *docPath=[NSSearchPathForDirectoriesInDomains((NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSString *myDirPath=[docPath stringByAppendingPathComponent:@"myDir"];
//讀字符串內容
NSString *myFilePath=[myDirPath stringByAppendingPathComponent:@"myFile.txt"];
NSString *content=[NSString stringWithContentsOfFile:myFilePath encoding:NSUTF8StringEncoding error:nil];
/*讀數組內容
NSString *myFilePath=[myDirPath stringByAppendingPathComponent:@"myFile.txt"];
NSArray *content=[NSArray arrayWithContentsOfFile:myFilePath];
*/
/*讀字典內容
NSString *myFilePath=[myDirPath stringByAppendingPathComponent:@"myFile.plist"];
NSDictionary *content=[[NSDictionary alloc]initWithContentsOfFile:myFilePath];
*/
/*讀混合數據
NSString *myFilePath=[myDirPath stringByAppendingPathComponent:@"myFile.txt"];
int intData;
float floatData = 0.0;
NSString *stringData;
NSData *reader = [NSData dataWithContentsOfFile:myFilePath];
stringData = [[NSString alloc] initWithData:[reader subdataWithRange:NSMakeRange(0, [temp length])] encoding:NSUTF8StringEncoding];
[reader getBytes:&intData range:NSMakeRange([temp length], sizeof(intData))];
[reader getBytes:&floatData range:NSMakeRange([temp length] + sizeof(intData), sizeof(floatData))];
*/atom
刪除文件:
NSFileManager *fileManager=[NSFileManager defaultManager];
NSString *docPath=[NSSearchPathForDirectoriesInDomains((NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSString *myDirPath=[docPath stringByAppendingPathComponent:@"myDir"];
NSString *myFilePath=[myDirPath stringByAppendingPathComponent:@"myFile.txt"];
BOOL result=[fileManager removeItemAtPath:myFilePath error:nil];
if(result){
NSLog(@"文件刪除成功");
}else{
NSLog(@"文件刪除失敗");
}
修改文件:
把新數據寫入到舊數據相應路徑上覆蓋便可component
判斷文件是否存在:
NSFileManager *fileManager=[NSFileManager defaultManager];
NSString *docPath=[NSSearchPathForDirectoriesInDomains((NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSString *myDirPath=[docPath stringByAppendingPathComponent:@"myDir"];
NSString *myFilePath=[myDirPath stringByAppendingPathComponent:@"myFile.txt"];
BOOL isHad=[fileManager isExecutableFileAtPath:myFilePath];
if(isHad){
NSLog(@"文件存在");
}else{
NSLog(@"文件不存在");
}對象
NSFileManager經常使用方法:
-(BOOL)removeItemAtPath:(NSString *)path error:(NSError **)error
將path所表明的文件刪除rem
-(BOOL)moveItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath error:(NSError **)error
移動或者重命名文件,to所表明的文件不能是已經存在的文件字符串
-(BOOL)contentsEqualAtPath:path1 andPath:path2
比較path1和path2所表明的文件
-(BOOL)fileExistsAtPath:path
檢查path所表明的文件是否存在
-(BOOL)isReadableFileAtPath:path
檢查path所表明的文件是否存在、是否可讀
-(BOOL)isWritableFileAtPath:path
檢查path所表明的文件是否存在、是否可寫
-(NSDictionary *)fileAttributesAtPath:path traverseLink:(BOOL)flag
獲取path所表明的文件屬性
-(BOOL)changeFileAttributes:attr atPath:path
改變文件屬性
-(NSString *)currentDirectoryPath
獲取當前目錄
-(BOOL)changeCurrentDirectoryPath:path
更改當前目錄
-(BOOL)copyItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath error:(NSError **)error
複製目錄結構,to不能已經存在
-(BOOL)createDirectoryAtPath:path attributes:attr
建立目錄
-(BOOL)fileExistsAtPath:(NSString *)path;
路徑文件是否存在
-(BOOL)fileExistsAtPath:path isDirectory:(BOOL *)flag
測試文件是否爲目錄 (flag存儲結構yes/no)
-(NSArray *)contentsOfDirectoryAtPath:(NSString *)path error:(NSError **)error
列出目錄的內容
-(NSDirectoryEnumerator *)enumeratorAtPath:path
枚舉目錄的內容
-(BOOL)removeFileAtPath:path handler:handler
刪除空目錄
經常使用路徑(NSString對象)工具方法
-(NSString *) pathWithComponents:components
根據components中元素構造有效路徑
-(NSArray *)pathComponents
析構路徑,獲取路徑的各個部分
-(NSString *)lastPathComponent
提取路徑的最後一個組成部分
-(NSString *)pathExtension
路徑擴展名
-(NSString *)stringByAppendingPathComponent:path
將path添加到現有路徑末尾
-(NSString *)stringByAppendingPathExtension:ext
將拓展名添加的路徑最後一個組成部分
-(NSString *)stringByDeletingPathComponent
刪除路徑的最後一個部分
-(NSString *)stringByDeletingPathExtension
刪除路徑的最後一個部分 的擴展名
-(NSString *)stringByExpandingTildeInPath
將路徑中的代字符擴展成用戶主目錄(~)或指定用戶主目錄(~user)
-(NSString *)stringByResolvingSymlinksInPath
嘗試解析路徑中的符號連接
-(NSString *)stringByStandardizingPath
經過嘗試解析~、..、.、和符號連接來標準化路徑
NSFileHandle方法
+(NSFileHandle *)fileHandleForReadingAtPath:path
打開一個文件準備讀取
+(NSFileHandle *)fileHandleForWritingAtPath:path
打開一個文件準備寫入
+(NSFileHandle *)fileHandleForUpdatingAtPath:path
打開一個文件準備更新(讀取和寫入)
-(NSData *)availableData
從設備或通道返回可用數據
-(NSData *)readDataToEndOfFile
讀取其他的數據直到文件末尾(最多UINT_MAX字節)
-(NSData *)readDataOfLength:(unsigned int)bytes
從文件讀取指定數目bytes的內容
-(void)writeData:data
將data寫入文件
-(unsigned long long) offsetInFile
獲取當前文件的偏移量
-(void)seekToFileOffset:offset
設置當前文件的偏移量
-(unsigned long long) seekToEndOfFile
將當前文件的偏移量定位的文件末尾
-(void)truncateFileAtOffset:offset
將文件的長度設置爲offset字節
-(void)closeFile
關閉文件
使用示範:
//要定位到文件 (文件的句柄爲databaseHandle)的第10個字節
[databaseHandle seekToFileOffset:10];
//獲得相對文件位置,經過得到當前的文件偏移量,而後加上或者減去這個值
[databaseHandle seekToFileOffset:[databaseHandle offsetInFile] + 128];
//在文件中向回移動5個整數所佔的子結束
[databaseHandle seekToFileOffset:[databaseHandle offsetInFile] -5 * sizeof(int)];
//向文件追加數據
NSString *homePath = NSHomeDirectory( );
NSString *sourcePath = [homePath stringByAppendingPathConmpone:@"testfile.text"];
NSFileHandle *fielHandle = [NSFileHandle fileHandleForUpdatingAtPath:sourcePath];
[fileHandle seekToEndOfFile]; 將節點跳到文件的末尾
NSString *str = @"追加的數據"
NSData* stringData = [str dataUsingEncoding:NSUTF8StringEncoding];
[fileHandle writeData:stringData]; 追加寫入數據
[fileHandle closeFile];
//定位數據
NSFileManager *fm = [NSFileManager defaultManager];
NSString *content = @"abcdef";
[fm createFileAtPath:path contents:[content dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];
NSFileHandle *fileHandle = [NSFileHandle fileHandleForReadingAtPath:path];
NSUInteger length = [fileHandle availabelData] length]; 獲取數據長度
[fileHandle seekToFileOffset;length/2]; 偏移量文件的一半
NSData *data = [fileHandle readDataToEndOfFile];
[fileHandle closeFile];
//複製文件 NSFileHandle *infile, *outfile; 輸入文件、輸出文件 NSData *buffer; 讀取的緩衝數據 NSFileManager *fileManager = [NSFileManager defaultManager]; NSString *homePath = NSHomeDirectory( ); NSString *sourcePath = [homePath stringByAppendingPathComponent:@"testfile.txt"]; 源文件路徑 NSString *outPath = [homePath stringByAppendingPathComponent:@"outfile.txt"]; 輸出文件路徑 BOOL sucess = [fileManager createFileAtPath:outPath contents:nil attributes:nil]; if (!success){ return N0; } infile = [NSFileHandle fileHandleForReadingAtPath:sourcePath]; 建立讀取源路徑文件 if (infile == nil){ return NO; } outfile = [NSFileHandle fileHandleForReadingAtPath:outPath]; 建立病打開要輸出的文件 if (outfile == nil){ return NO; } [outfile truncateFileAtOffset:0]; 將輸出文件的長度設爲0 buffer = [infile readDataToEndOfFile]; 讀取數據 [outfile writeData:buffer]; 寫入輸入 [infile closeFile]; 關閉寫入、輸入文件 [outfile closeFile];