【发布时间】:2015-09-18 12:13:54
【问题描述】:
我正在开发将视频文件保存在 iOS 应用程序文件夹中的功能。
如何以编程方式重命名某些文件?
【问题讨论】:
-
@Darshan 谢谢你的建议。
标签: ios objective-c file-rename
我正在开发将视频文件保存在 iOS 应用程序文件夹中的功能。
如何以编程方式重命名某些文件?
【问题讨论】:
标签: ios objective-c file-rename
试试这个代码:
NSError * err = NULL;
NSFileManager * fm = [[NSFileManager alloc] init];
BOOL result = [fm moveItemAtPath:@"/tmp/test.tt" toPath:@"/tmp/dstpath.tt" error:&err];
if(!result)
NSLog(@"Error: %@", err);
否则使用此方法重命名文件
- (void)renameFileWithName:(NSString *)srcName toName:(NSString *)dstName
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePathSrc = [documentsDirectory stringByAppendingPathComponent:srcName];
NSString *filePathDst = [documentsDirectory stringByAppendingPathComponent:dstName];
NSFileManager *manager = [NSFileManager defaultManager];
if ([manager fileExistsAtPath:filePathSrc]) {
NSError *error = nil;
[manager moveItemAtPath:filePathSrc toPath:filePathDst error:&error];
if (error) {
NSLog(@"There is an Error: %@", error);
}
} else {
NSLog(@"File %@ doesn't exists", srcName);
}
}
【讨论】:
没有用于重命名文件的直接 API。虽然当您将文件从一个地方移动到另一个地方时,如果目标路径中的该文件不存在,那么 iOS 将以给定名称创建该文件。对于文件,您可以只给出文件的新名称,它应该如何显示/引用。
【讨论】: