iOS NSFileManeger 計算文件是否超時,和計算文件夾下文件的總大小

xpkdi 9年前發布 | 875 次閱讀 C/C++ IOS

//獲得指定文件距離上次修改時間是否達到了指定值(秒)timeout

+(BOOL)isTimeout:(NSString *)path time:(NSTimeInterval)timeout

{

//獲得當前時間

NSTimeInterval now = [[NSDate date] timeIntervalSince1970];



NSDictionary *dict = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil];

// 取得了文件上次修改的時間

NSDate *d = [dict objectForKey:NSFileModificationDate];

if (now-[d timeIntervalSince1970]>timeout) {

    return YES;

}

return NO;

}

//計算文件夾下文件的總大小

+(float)fileSizeForDir:(NSString*)path

{

NSFileManager *fileManager = [NSFileManager defaultManager];



//記錄總值

unsigned long long totalSize =0;

//獲得指定路徑path的所有內容(文件和文件夾)

NSArray* array = [fileManager contentsOfDirectoryAtPath:path error:nil];

for(int i = 0; i<[array count]; i++)

{

    //拼接全路徑

    NSString *fullPath = [path stringByAppendingPathComponent:[array objectAtIndex:i]];

    BOOL isDir;



    //如果指定路徑存在并且不是文件夾

    //NSLog(@"fullPath:%@",fullPath);

    //先判斷是否存在,再判斷是文件夾還是文件

    if ([fileManager fileExistsAtPath:fullPath isDirectory:&isDir] && !isDir)

    {

        //獲得文件屬性

        NSDictionary *fileAttributeDic=[fileManager attributesOfItemAtPath:fullPath error:nil];

        totalSize+=[[fileAttributeDic objectForKey:NSFileSize] unsignedLongLongValue];

    }

    else

    {

        //如果是文件夾,遞歸

        totalSize+=[self fileSizeForDir:fullPath];

    }

}

return totalSize;

}

</pre>

 本文由用戶 xpkdi 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!