【发布时间】:2010-02-09 03:40:30
【问题描述】:
给定一个目录[[self documentsDirectory] stringByAppendingPathComponent:@"Photos/"]我如何删除这个文件夹中的所有文件?
(假设一个正确的文档目录路径)
【问题讨论】:
标签: iphone objective-c cocoa-touch filesystems
给定一个目录[[self documentsDirectory] stringByAppendingPathComponent:@"Photos/"]我如何删除这个文件夹中的所有文件?
(假设一个正确的文档目录路径)
【问题讨论】:
标签: iphone objective-c cocoa-touch filesystems
NSFileManager *fm = [NSFileManager defaultManager];
NSString *directory = [[self documentsDirectory] stringByAppendingPathComponent:@"Photos/"];
NSError *error = nil;
for (NSString *file in [fm contentsOfDirectoryAtPath:directory error:&error]) {
BOOL success = [fm removeItemAtPath:[NSString stringWithFormat:@"%@%@", directory, file] error:&error];
if (!success || error) {
// it failed.
}
}
如果存在错误,我会让你做一些有用的事情。
【讨论】:
stringByAppendingPathComponent 而不是stringWithFormat 来连接路径。 (我知道上述方法有效,但这只是因为您在@"Photos/" 中硬编码的斜杠。)
stringByAppendingPathComponent 很重要,特别是如果你在 iOS 上使用它。
stringByAppendingPathComponent从@"Photos/"中剥离了硬编码的斜线,这样当你稍后尝试使用directory变量时,它不包括应将其与file 分开的斜线。快速解决方法是在创建 directory 变量时删除硬编码的尾部斜杠,并将斜杠添加到 %@%@ 之间的 stringWithFormat 调用中
[fm contentsOfDirectoryAtPath:directory error:&error] 移出for 循环,这样它就不会在每次迭代时调用该方法。类似NSArray<NSString*> *contents = [fm contentsOfDirectoryAtPath:documentsPath error:&error]; 和for (NSString *file in contents)
如果你想删除文件和目录本身,那么在没有for循环的情况下使用它
NSFileManager *fm = [NSFileManager defaultManager];
NSString *directory = [[self documentsDirectory] stringByAppendingPathComponent:@"Photos"];
NSError *error = nil;
BOOL success = [fm removeItemAtPath:cacheImageDirectory error:&error];
if (!success || error) {
// something went wrong
}
【讨论】:
速成爱好者也一样:
let fm = FileManager.default
do {
let folderPath = "...my/folder/path"
let paths = try fm.contentsOfDirectory(atPath: folderPath)
for path in paths
{
try fm.removeItem(atPath: "\(folderPath)/\(path)")
}
} catch {
print(error.localizedDescription)
}
【讨论】:
大多数较旧的答案都让您使用contentsOfDirectoryAtPath:error:,这会起作用,但according to Apple:
“指定文件或目录位置的首选方法是使用 NSURL 类”
所以如果你想使用 NSURL 代替,你可以使用方法contentsOfDirectoryAtURL:includingPropertiesForKeys:options:error:,所以它看起来像这样:
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray<NSURL*> *urls = [fileManager contentsOfDirectoryAtURL:directoryURL includingPropertiesForKeys:@[NSURLNameKey, NSURLIsDirectoryKey] options:NSDirectoryEnumerationSkipsHiddenFiles error:nil];
for (NSURL *url in urls)
{
NSError *error = nil;
BOOL success = [fileManager removeItemAtURL:url error:error];
if (!success || error) {
// something went wrong
}
}
【讨论】:
斯威夫特 4
do {
let destinationLocation:URL = ...
if FileManager.default.fileExists(atPath: destinationLocation.path) {
try! FileManager.default.removeItem(at: destinationLocation)
}
} catch {
print("Error \(error.localizedDescription)")
}
【讨论】:
fileExists(atPath:) 上查看the documentation 了解更多信息。