天天看點

【ios 彙總 - 操作檔案常用方法】 (NSFileManager NSFileHandle NSData)在檔案末位寫入data seekToEndOfFile建立檔案夾 createDirectoryAtPath周遊檔案夾下所有檔案擷取md5 再轉字元串按長度添加data  擷取bundle 檔案路徑

在檔案末位寫入data seekToEndOfFile

                NSFileHandle* fileHandle = [NSFileHandlefileHandleForWritingAtPath:cfg.tmpPath];

                if (fileHandle)

                {

                    [fileHandle seekToEndOfFile];

                    if (item.data.length >0)

                    {

                        [fileHandle writeData:item.data];

                        item.writeTotalLen += item.data.length;

                    }

                    if (addData)

                    {

                        [fileHandle writeData:addData];

                        item.writeTotalLen += addData.length;

                    }

                    [fileHandle closeFile];

                    [item.data resetBytesInRange:NSMakeRange(0, item.data.length)];

                    [item.data setLength:0];

                }

建立檔案夾 createDirectoryAtPath

    NSFileManager* fileManager = [NSFileManagerdefaultManager];

    BOOL exists = [fileManager fileExistsAtPath:directory isDirectory:&isDirectory];

bSuccess = [fileManager createDirectoryAtPath:directorywithIntermediateDirectories:YESattributes:nilerror:&err];

周遊檔案夾下所有檔案

- (NSMutableArray *)showAllLogFileName

{

    NSString *logPath = [NSString stringWithFormat:@"%@/log/", [NSString CachePath]];

    NSFileManager *fm = [NSFileManager defaultManager];

    NSArray *logs = [fm contentsOfDirectoryAtPath:logPath error:nil];

    NSMutableArray *logFiles = [NSMutableArray array];

    if([logs count]){

        [logs sortedArrayUsingSelector:@selector(compare:)];

        for (id objin [logs reverseObjectEnumerator]) {

            [logFiles addObject:obj];

        }

    }

    return logFiles;

}

擷取md5 再轉字元串

CC_MD5(cStr, (CC_LONG)strlen(cStr), result);

NSString* key = [NSStringstringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",result[0], result[1], result[2], result[3], result[4], result[5], result[6], result[7],result[8], result[9], result[10], result[11],result[12], result[13], result[14], result[15]];

按長度添加data  

(機關:byte)

[thisItem.data appendBytes:result.data.byteslength:nlen];

擷取bundle 檔案路徑

    resourcePath = [[[[ NSBundle  mainBundle] resourcePath]stringByAppendingPathComponent:@"Bird"]

                    stringByAppendingPathComponent:@"index.html"];

繼續閱讀