(1)获取应用程序的目录
NSString * filepath = NSHomeDirectory();//当前工程目录
NSLog(@"当前文件路径:%@",filepath);
打印结果:
2)通过追加字符串,获取文件绝对路径
//通过追加字符串,获取文件绝对路径
filepath = [filepath stringByAppendingPathComponent:@"Desktop/12/test/test/test.txt"];
NSLog(@"文件路径:%@",filepath);
//返回文件的组成部分
// NSArray *array = [filepath pathComponents];
// NSLog(@"文件的组成部分:%@",array);
NSFileManager *file = [NSFileManager defaultManager];
if ([file fileExistsAtPath:filepath]) {
NSLog(@"文件已存在");
}else{
BOOL sucess = [file createFileAtPath:filepath contents:nil attributes:nil];
if (sucess == 1) {
NSLog(@"文件创建成功");
}else{
NSLog(@"文件创建失败");
}
}
//向文件里面写数据,写数据之前把字符串转换成UTF8编码并且存起来
NSError *error=nil;
NSString *data = @"ascavdsvfsbfsb";
[data writeToFile:filepath atomically:YES encoding:NSUTF8StringEncoding error:&error];
//向文件里面写数据,写数据之前把字符串转换成UTF8编码并且存起来
NSError *error=nil;
NSString *data = @"ascavdsvfsbfsb";
[data writeToFile:filepath atomically:YES encoding:NSUTF8StringEncoding error:&error];
// NSLog(@"Documentsdirectory: %@",[file contentsAtPath:filepath]);
//跳到文件末尾
NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:filepath];
[fileHandle seekToEndOfFile];
NSData * u =[fileHandle readDataToEndOfFile] ;
NSString *str = [[NSString alloc] initWithData:u encoding:NSUTF8StringEncoding];
NSLog(@"data = %@",str);
文件相关操作:
+(NSFileHandle *)fileHandleForReadingAtPath:path 打开文件以便读取
+(NSFileHandle *)fileHandleForWritingAtPath:path 打开文件以便写入
+(NSFileHandle *)fileHandleForUpdatingAtPath:path 打开文件以便读写
-(NSData *)availableData 产生的结果为其实施对象中可用的数据
-(NSData *)readDataToEndOfFile 读取文件末尾处之前的数据
-(NSData *)readDataOfLength:(NSUInteger)bytes 读取长度为bytes字节的数据
-(void)writeData:data 将数据data写入文件
-(unsigned long long)offsetInFile 获取当前文件中的操作位置
-(void)seekToFileOffset:offset 将当前文件的操作位置设定为offset
-(unsigned long long)seekToEndOfFile 将当前文件的操作位置设定为文件的末尾处
-(void)truncateFileAtOffset:offset 将文件的长度设定为offset
-(void)closeFile 关闭文件