// 创建一个文件
- (void)addField
{
NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *fieldPath = [documentPath stringByAppendingPathComponent:@"student.txt"];
NSLog(@"%@",fieldPath);
NSString *txt = @"wanglong";
[txt writeToFile:fieldPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
// 从路径中 读取文件 获取NSFileHandle对象
NSFileHandle *handle = [NSFileHandle fileHandleForUpdatingAtPath:fieldPath];
// 获取文件内容的 结束偏移量
unsigned long long endOffset = handle.seekToEndOfFile;
[handle seekToFileOffset:4];
// 获取当前的偏移量 初始偏移量为0
unsigned long long offset = handle.offsetInFile;
// 准备要写入的字符串
NSString *str = @"123";
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
[handle writeData:data];
NSString *saveStr = [NSString stringWithContentsOfFile:fieldPath encoding:NSUTF8StringEncoding error:nil];
NSLog(@"%@",saveStr);
// -------------------------------------------------------
// 覆盖数据
NSFileHandle * srcFile, * destFile; // 输入文件、输出文件
NSData * buffer;// 读取的缓冲数据
NSFileManager * manager = [NSFileManager defaultManager];
NSString * sourcePath = [documentPath stringByAppendingPathComponent:@"sourceFile.txt"];// 源文件路径
NSLog(@"%@",sourcePath);
[manager createFileAtPath:sourcePath contents:[@"Hello" dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];
NSString * destPath = [documentPath stringByAppendingPathComponent:@"destFile.txt"];// 输出文件路径
BOOL success = [manager createFileAtPath:destPath contents:[@"abcdef" dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];
if (!success) {
return;
}
srcFile = [NSFileHandle fileHandleForReadingAtPath:sourcePath];
if (!destFile) {
return;
}
destFile = [NSFileHandle fileHandleForWritingAtPath:destPath];
if (!destFile) {
return;
}
[destFile truncateFileAtOffset:0];// 将输出文件的长度设为0,(也就是将原来的文件清空)
buffer = [srcFile readDataToEndOfFile];// 读取数据
[destFile writeData:buffer];
[srcFile closeFile];
[destFile closeFile];
}