我是iphone的新手,请帮助我,我想使用iphone从textfile中读取文本现在能够从txtfile中读取文本,但我的问题是(在txtfile中保存了一些数据,如“欢迎使用webapps”这些文字)我想只读webapp字符串) 通过使用此代码,我读取来自txtfile.please的所有数据,只提供读取指定文本的任何想法。
-(NSString *)readFile:(NSString *)fileName {
NSString *filePath = [[NSBundle mainBundle] pathForResource:fileName ofType:@"txt"];
NSData *myData = [NSData dataWithContentsOfFile:filePath];
NSString *str,*docStr;
if (myData) {
str = [[NSString alloc] initWithData:myData encoding:NSASCIIStringEncoding];
}
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
// the path to write file
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:fileName];
NSError *error = nil;
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:appFile];
if(fileExists)
{
NSLog(@"file exist in document");
NSData *myData1 = [NSData dataWithContentsOfFile:appFile];
if (myData1) {
docStr = [[NSString alloc] initWithData:myData1 encoding:NSASCIIStringEncoding];
}
}
else {
NSLog(@"file does not exist");
BOOL success = [str writeToFile:appFile atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (!success) {
NSLog(@"Error: %@", [error userInfo]);
}
else {
NSLog(@"File write is successful");
}
NSData *myData1 = [NSData dataWithContentsOfFile:appFile];
if (myData1) {
docStr = [[NSString alloc] initWithData:myData1 encoding:NSASCIIStringEncoding];
}
}
return docStr;
}
答案 0 :(得分:0)
NSString *mystring=[docstr substringFromIndex:11];
在mystring中你将拥有“webapps”