您的位置:首页 > 移动开发 > IOS开发

NSFileManager的常用操作

2016-01-10 23:13 399 查看
1.) 删除文件

   

NSFileManager
*fn = [NSFileManager

defaultManager];

    [fn
removeItemAtPath:filePath
error:nil];

判断文件是否存在

 if
(![[NSFileManager

defaultManager]

fileExistsAtPath:_filePath])
{

           
//先创建临时文件夹,这个方法如果文件会补全路劲文件夹,如果已存在则不新建文件夹

           

NSString
*dirPath = [NSHomeDirectory()

stringByAppendingFormat:@"/Documents/tmp"];

            [[NSFileManager

defaultManager]

createDirectoryAtPath:dirPath

withIntermediateDirectories:YES

attributes:nil

error:nil];

           
//创建空的临时文件

            [[NSFileManager

defaultManager]

createFileAtPath:_filePath

contents:nil

attributes:nil];

        }

2). 文件句柄

- (void)appendData:(NSData
*)data

{

   
NSString
*filePath = [NSHomeDirectory()

stringByAppendingFormat:@"/Documents/data"];

   
//
判断文件是否存在

    NSFileHandle
*fp = [NSFileHandle

fileHandleForWritingAtPath:filePath];

   
//
如果文件不存在创建文件

   
if (!fp) {

        [data
writeToFile:filePath

atomically:YES];

    }
else {

       
//
如果文件已经存在追加文件

       
// 1>
移动到文件末尾

        [fp seekToEndOfFile];

       
// 2>
追加数据

        [fp writeData:data];

       
// 3>
写入文件

        [fp closeFile];

    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  IOS 文件 保存