// // TextHander.h // OC10_文件练习 // // Created by zhangxueming on 15/6/19. // Copyright (c) 2015年 zhangxueming. All rights reserved. // #import <Foundation/Foundation.h> @interface TextHander : NSObject + (void)replaceStringInTextFile:(NSString *)path withOldString:(NSString *)dstString toNewString:(NSString *)newString; + (void)replaceStringInDirectory:(NSString *)path withOldString:(NSString *)dstString toNewString:(NSString *)newString fileType:(NSString *)type; @end
// // TextHander.m // OC10_文件练习 // // Created by zhangxueming on 15/6/19. // Copyright (c) 2015年 zhangxueming. All rights reserved. // #import "TextHander.h" @implementation TextHander + (void)replaceStringInTextFile:(NSString *)path withOldString:(NSString *)dstString toNewString:(NSString *)newString { //备份文件 /name /name_bak NSFileManager *fm = [NSFileManager defaultManager]; [fm copyItemAtPath:path toPath:[path stringByAppendingString:@"_bak"] error:nil]; //1.创建文件句柄 NSFileHandle *fh = [NSFileHandle fileHandleForUpdatingAtPath:path]; //2.读取文件 NSData *data = [fh readDataToEndOfFile]; NSString *dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; //3.替换内容 dataString = [dataString stringByReplacingOccurrencesOfString:dstString withString:newString]; //4.文件清空 [fh truncateFileAtOffset:0]; //5.写文件 [fh writeData:[dataString dataUsingEncoding:NSUTF8StringEncoding]]; //6.同步文件 [fh synchronizeFile]; //7.关闭文件 [fh closeFile]; } + (void)replaceStringInDirectory:(NSString *)path withOldString:(NSString *)dstString toNewString:(NSString *)newString fileType:(NSString *)type { //1.遍历目录 NSFileManager *fm = [NSFileManager defaultManager]; NSArray *contents = [fm subpathsOfDirectoryAtPath:path error:nil]; // /dic/filename.txt //2.遍历数组 找到指定类型的文件 for (NSString *item in contents) { NSString *name = [item pathExtension]; if ([name isEqualToString:type]) { [self replaceStringInTextFile:[path stringByAppendingFormat:@"/%@",item] withOldString:dstString toNewString:newString]; } } } @end
// // main.m // OC10_文件练习 // // Created by zhangxueming on 15/6/19. // Copyright (c) 2015年 zhangxueming. All rights reserved. // #import <Foundation/Foundation.h> #import "TextHander.h" //把path指定的文件中的字符串 "him" 替换为 "me” //[LZXTextHandle replaceStringInTextFile:FILE_PATH withOldString:@"him" toNewString:@"me"]; //以下代码的作用: //把path指定的文件夹中的txt文件中的字符串"him"替换为字符串"me" //[LZXTextHandle replaceStringInDirectory:DIR_PATH withOldString:@"him" toNewString:@"me" fileType:@"txt"]; int main(int argc, const char * argv[]) { @autoreleasepool { // insert code here... //NSLog(@"Hello, World!"); //[TextHander replaceStringInTextFile:@"/Users/zhangxueming/Desktop/Test/3.txt" withOldString:@"him" toNewString:@"me"]; [TextHander replaceStringInDirectory:@"/Users/zhangxueming/Desktop/Test" withOldString:@"him" toNewString:@"me" fileType:@"txt"]; } return 0; }