IOS檢測指定路徑的文件是否存在
更新時間:2015年05月27日 10:06:13 投稿:hebedich
本文給大家分享的是在IOS開發(fā)中檢測指定文件是否存在的方法,給大家匯總了4種,十分實用,小伙伴們根據(jù)自己的需求自由選擇吧。
復制代碼 代碼如下:
- (NSString *)dataPath:(NSString *)file
{
NSString *path = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"badge"];
BOOL bo = [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
NSAssert(bo,@"創(chuàng)建目錄失敗");
NSString *result = [path stringByAppendingPathComponent:file];
return result;
}
- (void)viewDidLoad
{
[super viewDidLoad];
//此處首先指定了圖片存取路徑(默認寫到應用程序沙盒 中)
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
//并給文件起個文件名
NSString *imageDir = [[[paths objectAtIndex:0] stringByAppendingPathComponent:@"163"] stringByAppendingPathComponent:@"songzi"];
//存放圖片的文件夾
NSString *imagePath =[imageDir stringByAppendingPathComponent:@"文件名.png"];
NSData *data = nil;
//檢查圖片是否已經(jīng)保存到本地
if([self isExistsFile:imagePath]){
data=[NSData dataWithContentsOfFile:imagePath];
}else{
data = [NSData dataWithContentsOfURL:[NSURL URLWithString: @"網(wǎng)址"]];
//創(chuàng)建文件夾路徑
[[NSFileManager defaultManager] createDirectoryAtPath:imageDir withIntermediateDirectories:YES attributes:nil error:nil];
//創(chuàng)建圖片
[UIImagePNGRepresentation([UIImage imageWithData:data]) writeToFile:imagePath atomically:YES];
}
imageView.image = [UIImage imageWithData:data];
}
檢查文件是否存在
復制代碼 代碼如下:
NSString *path = [[NSBundle mainBundle] pathForResource:fileName ofType:@""];
if(path==NULL)
方法二:
復制代碼 代碼如下:
NSFileManager *fileManager = [NSFileManager defaultManager];
//Get documents directory
NSArray *directoryPaths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [directoryPaths objectAtIndex:0];
if ([fileManager fileExistsAtPath:@""]==YES) {
NSLog(@"File exists");
}
方法三:
復制代碼 代碼如下:
//判斷文件是否存在
if(![c judgeFileExist:@"user.plist"])
{
NSLog(@"請確認該文件是否存在!");
return;
}
方法四:
復制代碼 代碼如下:
//判斷文件是否存在
-(BOOL)judgeFileExist:(NSString * )fileName
{
//獲取文件路徑
NSString *path = [[NSBundle mainBundle] pathForResource:fileName ofType:@""];
if(path==NULL)
return NO;
returnYES;
}
相關(guān)文章
ios 11和iphone x的相關(guān)適配問題及解決方法
這篇文章主要介紹了ios 11和iphone x的相關(guān)適配,文中給大家提到了在ios 11中,tableView會莫名偏移問題的解決方法,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2017-11-11
iOS中定位(location manager )出現(xiàn)log日志的解決辦法
這篇文章主要給大家介紹了關(guān)于iOS中定位(location manager )出現(xiàn)log日志的解決辦法,文中通過示例代碼將解決的辦法介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面來一起學習學習吧。2017-10-10
iOS開發(fā)中Quartz2D控制圓形縮放和實現(xiàn)刷幀效果
這篇文章主要介紹了iOS開發(fā)中Quartz2D控制圓形縮放和實現(xiàn)刷幀效果的方法,代碼基于傳統(tǒng)的Objective-C,需要的朋友可以參考下2015-12-12
iOS關(guān)鍵字static extern const使用示例詳解
這篇文章主要為大家介紹了iOS關(guān)鍵字static extern const使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-11-11

