【Demo 0024】FoundationKit 文件操作
一、NSFileHandle 介绍
NSFileHandle 类提供文件IO操作的类, 打开文件,关闭文件,读写文件,文件指针重定位等;
二、文件操作常用方法
1. 打开文件
fileHandleForReadingAtPath
fileHandleForWritingAtPath
fileHandleForUpdatingAtPath
2. 读写文件
readDataToEndOfFile
readDataOfLength
writeData
3. 文件指针定位
offsetInFile
seekToFileOffset
seekToEndOfFile
truncateFileAtOffset
4. 关闭文件
closeFile
三、练习代码
@autoreleasepool {
NSString* fileName = NSTemporaryDirectory();
NSString* txtPath = [[fileName stringByAppendingPathComponent:@"testfile"]stringByAppendingPathExtension:@"txt"];
NSString* newPath = [[fileName stringByAppendingPathComponent:@"newfile"]stringByAppendingPathExtension:@"txt"];
NSURL* url = [NSURLURLWithString:@"http://www.baidu.com"];
// create source file
NSData* data = [NSData dataWithContentsOfURL:url];
NSFileManager* fm = [NSFileManagerdefaultManager];
[fm createFileAtPath:txtPath contents:data attributes:nil];
[fm createFileAtPath:newPath contents:nilattributes:nil];
NSLog(@"data save to %@", txtPath);
NSFileHandle* fileReading = [NSFileHandle fileHandleForReadingAtPath: txtPath];
NSFileHandle* fileWriting = [NSFileHandle fileHandleForUpdatingAtPath: newPath];
if (![fm isReadableFileAtPath:txtPath])
{
NSLog(@"file is not readable");
return 0;
}
if (![fm isWritableFileAtPath:newPath])
{
NSLog(@"file is not writabel");
return 0;
}
NSData* tmpData = [fileReading readDataToEndOfFile];
[fileWriting writeData:tmpData];
NSLog(@"%@ file lenght: %lu", newPath, [tmpData length]);
[fileWriting writeData:tmpData];
[fileWriting seekToFileOffset:10];
NSString* info = @"2013.3.6 ztercel";
NSData* data2 = [NSData dataWithBytes: [info UTF8String] length:[info length]];
[fileWriting writeData:data2];
[fileReading closeFile];
[fileWriting closeFile];
[fm removeItemAtPath:txtPath error:nil];
[fm removeItemAtPath:newPath error:nil];
NSLog(@"handle successfully");
}
演示实例
浙公网安备 33010602011771号