標籤:
前言:因為本人要高仿一個app,從app中解壓asserts得到的所有圖片檔案,檔案名稱都帶有~iPhone這個幹擾的名字,為了去除這個~iPhone這個字串,所以本人寫了個簡答的批量更改所有檔案名稱的程式。
程式員就是應該會利用程式來幫自己偷懶,因為用到的很多方法不是很熟悉,也是花了點時間去熟悉NSFileManager的一些方法,所以寫下這個筆記做個筆記,省的下次又需要就忘記了方法。
我的基本需求,在囉嗦一下下哈:
一個檔案目錄下有上百個圖片檔案,檔案名稱都帶有~iPhone。寫一個程式,刪除所有這個字串~iPhone。
代碼:
這個代碼利用了第三方別人封裝好的Regex類,然後再進一步實現我自己的需求
這個挺好用的Regex的類在github上:https://github.com/bendytree/Objective-C-RegEx-Categories
然後就是:
1 // 2 // main.m 3 // ChangeFileName 4 // 5 // Created by HEYANG on 16/4/3. 6 // Copyright © 2016年 HEYANG. All rights reserved. 7 // 8 // cnBlog:http://www.cnblogs.com/goodboy-heyang/ 9 // github:https://github.com/HeYang12345678910 //11 12 //-(BOOL)moveItemAtPath:from toPath:to error:err 重新命名或移動一個檔案(to 不能是已存在的)13 14 // 這裡輸入檔案目錄15 #define FileDirectory @"/Users/HeYang/Desktop/hello"16 17 18 #import <Foundation/Foundation.h>19 #import "RegExCategories.h"20 21 22 // 替換檔案名稱這個字串,去除檔案名稱中~iphone這個字眼23 NSString* changeString(NSString* string){24 // 直接使用Regex,替換掉25 NSString* result = [RX(@"~iphone") replace:string26 with:@""];27 return result;28 }29 30 // 擷取檔案名稱,並去除~iPhone31 NSString* getFileNameFromDirectory(NSString* directory)32 {33 NSFileManager* manager = [NSFileManager defaultManager];34 NSArray *dirArray = [manager contentsOfDirectoryAtPath:directory error:nil];35 for (NSString* str in dirArray) {36 // 原來的檔案目錄37 NSString* fromFileName = [FileDirectory stringByAppendingPathComponent:str];38 // 改變之後的檔案名稱39 NSString* changedStr = changeString(str);40 // 改變之後的檔案目錄41 NSString* toFileName = [FileDirectory stringByAppendingPathComponent:changedStr];42 // 替換,其實也是重新命名43 [manager moveItemAtPath:fromFileName toPath:toFileName error:nil];44 }45 return nil;46 }47 48 int main(int argc, const char * argv[]) {49 @autoreleasepool {50 51 getFileNameFromDirectory(FileDirectory);52 53 }54 return 0;55 }
項目源碼備份到百度雲連結: http://pan.baidu.com/s/1dFjUV5J 密碼: e5q9
用Objective-C寫了一個簡單的批量變更檔名的程式