object-c中对文件操作

 1 NSString *filePath = @"/Users/scjy/hello/iphone.txt";
 2         
 3         NSFileHandle *handle=[NSFileHandle fileHandleForUpdatingAtPath:filePath];//准备更新
 4         
 5         [handle seekToEndOfFile];//读取到文件末尾
 6         
 7         NSString *addString=@"尚承教育";
 8         
 9         NSData *data=[addString dataUsingEncoding:NSUTF8StringEncoding];//将字符串转换成data数据
10         
11         [handle writeData:data];//写入数据
12         
13         [handle closeFile];//关闭文件
14         
15         
16         //读取
17         NSFileHandle *handle1 = [NSFileHandle fileHandleForReadingAtPath:filePath];
18         NSData *data1 = [handle1 readDataToEndOfFile];
19         NSString *readString=[[NSString alloc]initWithData:data1 encoding:NSUTF8StringEncoding];
20         NSLog(@"%@",readString);
View Code
 1 //复制文件
 2         
 3         
 4         //找到原来的文件路径
 5         NSString *old_filePath = @"/Users/scjy/hello/iphone.txt";
 6         
 7         //指定新的文件路径(文件不存在)
 8         NSString *new_filePath = @"/Users/scjy/hello/ios.txt";
 9 
10         //创建文件管理器,为创建新的文件做准备
11         NSFileManager *fileManager=[NSFileManager defaultManager];
12         
13         //创建新的文件(此时文件中无数据)
14         BOOL isSuccess=[fileManager createFileAtPath:new_filePath contents:nil attributes:nil];
15         if (isSuccess) {
16             NSLog(@"创建成功");
17             
18             //1.读取原文件中的数据:fileHandleForReadingAtPath
19             NSFileHandle *old_handle=[NSFileHandle fileHandleForReadingAtPath:old_filePath];
20             NSData *old_data=[old_handle readDataToEndOfFile];
21             
22             //2.将原文件中获取的数据写入新的文件:fileHandleForWritingAtPath
23             NSFileHandle *new_handle=[NSFileHandle fileHandleForWritingAtPath:new_filePath];
24             [new_handle writeData:old_data];
25             
26             [old_handle closeFile];
27             [new_handle closeFile];
28             
29         }
30         else
31         {
32             NSLog(@"创建失败");
33         }
View Code
原文地址:https://www.cnblogs.com/doublelongliu/p/4645122.html