#import <Foundation/Foundation.h> @interface Utils : NSObject +(void) writeFile:(NSString *) filePath data:(NSString *) _data; +(NSString *) readFile:(NSString *) filePath; @end
#import "Utils.h" @implementation Utils +(void) writeFile:(NSString *) filePath data:(NSString *) _data{ NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString* fileName = [[paths objectAtIndex:0]stringByAppendingPathComponent:filePath]; NSLog(@"File %@ will write!", fileName); // 用这个方法来判断当前的文件是否存在,如果不存在,就创建一个文件 NSFileManager *fileManager = [NSFileManager defaultManager]; if ( ![fileManager fileExistsAtPath:fileName]) { NSLog(@"File %@ not exists!", fileName); [fileManager createFileAtPath:fileName contents:nil attributes:nil]; }else NSLog(@"File %@ exists!", fileName); [_data writeToFile:fileName atomically:YES encoding:NSUTF8StringEncoding error:NULL]; } +(NSString *) readFile:(NSString *) filePath{ NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString* fileName = [[paths objectAtIndex:0]stringByAppendingPathComponent:filePath]; NSLog(@"File %@ will write!", fileName); NSString* myString = [NSString stringWithContentsOfFile:fileName usedEncoding:NULL error:NULL]; return myString; } @end
调用:
[Utils writeFile:@"/Lein.txt" data:@"123QWE金属材料"]; NSLog(@"Lein.txt:%@", [Utils readFile:@"/Lein.txt"]);