【问题标题】:How to scan and replace content in text files如何扫描和替换文本文件中的内容
【发布时间】:2016-06-17 21:51:43
【问题描述】:

我需要写一个Mac项目,可以本地化.h文件中方法和属性的注解。

我可以使用代码

NSOpenPanel *panel = [NSOpenPanel openPanel];
[panel setAllowsMultipleSelection:YES];
[panel setMessage:@"Import one or more files or directories."];
[panel setCanChooseDirectories:YES];
[panel setDirectoryURL:[NSURL URLWithString:NSHomeDirectory()]];
[panel setAllowedFileTypes:[NSArray arrayWithObjects:@"h", nil]];

[panel beginWithCompletionHandler:^(NSInteger result) {

    if (result == NSFileHandlingPanelOKButton)
    {
        NSArray *urls = [panel URLs];
        NSLog(@"urls : %@",[urls description]);
    }
}];

获取文件的 URL。

但是我找不到扫描所有.h文件并获取.h文件内容的方法,更不用说交换注释了。非常感谢您的帮助,谢谢。

【问题讨论】:

  • 为什么不从命令行执行此操作?使用 UI 毫无意义。
  • NSOpenPanel 可以很好地获取文件的 URL。然后要打开、读取和写入文件,您需要一些其他类。

标签: macos cocoa text replace


【解决方案1】:

要读取、扫描和写入文本文件,使用NSMutableDatadataWithContentsOfURL 是最简单的:

然后用NSString之类的解析,见 Converting NSString to NSData and vice versa

https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSData_Class/#//apple_ref/occ/clm/NSData/dataWithContentsOfURL:

【讨论】:

    【解决方案2】:

    最后,我这样写代码:

    //1、扫描所有.h文件。

    -(NSArray *)filesWithSuffix:(NSString *)suffix atFilePath:(NSString *)path{
    NSFileManager * fileManager = [NSFileManager defaultManager];
    NSError * error;
    NSArray * array = [fileManager subpathsOfDirectoryAtPath:path error:&error];
    
    NSMutableArray *mutableArray = [NSMutableArray array];
    for (NSString *ele in array){
    
        if ([[ele substringFromIndex:(ele.length - suffix.length)] isEqualToString:suffix]){
            [mutableArray addObject:ele];
        }
    }
    return [mutableArray copy];}
    

    并调用方法:

    NSArray *filePaths = [self filesWithSuffix:@".h" atFilePath:path];
    

    【讨论】:

      猜你喜欢
      • 2016-01-10
      • 2015-11-28
      • 2017-03-23
      • 1970-01-01
      • 1970-01-01
      • 2021-12-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多