4
有什麼方法可以刪除給定目錄中的所有文件(不遞歸)使用模式?刪除與iOS中的模式匹配的文件
舉個例子,我有一個名爲file1.jpg
,file2.jpg
,file3.jpg
等一些文件,我想知道如果有一個acceps通配符這樣的UNIX命令的任何方法:
rm file*.jpg
有什麼方法可以刪除給定目錄中的所有文件(不遞歸)使用模式?刪除與iOS中的模式匹配的文件
舉個例子,我有一個名爲file1.jpg
,file2.jpg
,file3.jpg
等一些文件,我想知道如果有一個acceps通配符這樣的UNIX命令的任何方法:
rm file*.jpg
試試這個:
- (void)removeFiles:(NSRegularExpression*)regex inPath:(NSString*)path {
NSDirectoryEnumerator *filesEnumerator = [[NSFileManager defaultManager] enumeratorAtPath:path];
NSString *file;
NSError *error;
while (file = [filesEnumerator nextObject]) {
NSUInteger match = [regex numberOfMatchesInString:file
options:0
range:NSMakeRange(0, [file length])];
if (match) {
[[NSFileManager defaultManager] removeItemAtPath:[path stringByAppendingPathComponent:file] error:&error];
}
}
}
您例如
file1.jpg,file2.jpg,FIL e3.jpg
可以直接使用如下:
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^file.*\.jpg$"
options:NSRegularExpressionCaseInsensitive
error:nil];
[self removeFiles:regex inPath:NSHomeDirectory()];
斯威夫特版本
func removeFiles(regEx:NSRegularExpression, path:String) {
let filesEnumerator = NSFileManager.defaultManager().enumeratorAtPath(path)
while var file:String = filesEnumerator?.nextObject() as? String {
let match = regEx.numberOfMatchesInString(file, options: nil, range: NSMakeRange(0, file.length))
if match > 0 {
NSFileManager.defaultManager().removeItemAtPath(path.stringByAppendingPathComponent(file), error: nil)
}
}
}
輝煌!第二種解決方案簡直太棒了!謝謝! – SpaceDog 2011-05-31 02:17:38