这是您编写和读取文件文本所需的内容:
写一个文件:
-(void) writeStringToFile:(NSString *)aString{
NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *fileName = @"textFile.txt";
NSString *fileAtPath = [filePath stringByAppendingString:fileName];
if (![[NSFileManager defaultManager] fileExistsAtPath:fileAtPath]) {
[[NSFileManager defaultManager] createFileAtPath:fileAtPath contents:nil attributes:nil];
}
[[aString dataUsingEncoding:NSUTF8StringEncoding] writeToFile:fileAtPath atomically:NO];
}
并读取一个文件:
-(NSString *)readStringFromFile{
NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *fileName = @"textFile.txt";
NSString *fileAtPath = [filePath stringByAppendingString:fileName];
return [[NSString alloc] initWithData:[NSData dataWithContentsOfFile:fileAtPath] encoding:NSUTF8StringEncoding];
}
最后我在以下位置测试我的代码viewDidLoad
:
NSString *text = @"I'm an iOS developer and I'm living at HCM city";
[self writeStringToFile:text];
NSString *strResult = [self readStringFromFile];
NSLog(@"%@", strResult);