当您需要替换目标名称的现有文件(如果存在)时,更改文档目录中的文件名的现代 Swift 方法是什么?
(因此,我没有使用 moveItem...而是使用 ReplaceItem
很多年前关于这个问题有很多问题,例如这里,但我无法找到任何为我工作的问题。
例如:
let oldpicname = "22_contactpic.png"
let newpicname = "9213_contactpic.png"
do {
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let documentDirectory = URL(fileURLWithPath: path)
let originPath = documentDirectory.appendingPathComponent(oldpicname)
let destinationPath = documentDirectory.appendingPathComponent(newpicname)
try
print("try to replace file")
FileManager.default.replaceItemAt(originPath, withItemAt: destinationPath)
} catch {
print("FIRST TRY FAILED TO RENAME FILE")
print(error)
}
编译并且不会抛出错误,但是当我之后检查该文件时,它不存在。
上面链接中的 Matt 建议如下:
var rv = URLResourceValues()
rv.name = newname
try? url.setResourceValues(rv)
这给出了许多我无法解决的错误,包括你不能在不可变值上使用变异成员。
注意我可以在 Objective-C 中使用以下代码来完成此操作:
- (void)renameWithReplaceFileWithName:(NSString *)beforeName toName:(NSString *)afterName
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePathBefore = [documentsDirectory stringByAppendingPathComponent:beforeName];
NSString *filePathAfter = [documentsDirectory stringByAppendingPathComponent:afterName];
NSLog(@"filepath after is%@. This will be the new name of this file",filePathAfter);
NSFileManager *manager = [NSFileManager defaultManager];
if ([manager fileExistsAtPath:filePathBefore]) {
NSError *error = nil;
NSURL *previousItemUrl = [NSURL fileURLWithPath: filePathBefore];/
NSURL *currentItemUrl = [NSURL fileURLWithPath:filePathAfter];
[[NSFileManager defaultManager] replaceItemAtURL:previousItemUrl withItemAtURL:currentItemUrl backupItemName:nil options:0 resultingItemURL:nil error:&error];
if (error) {
// handle error
}
}
}
感谢您的任何建议。
这对我有用,可以更改文件名。
func replace() {
let oldpicname = "22_contactpic.png"
let newpicname = "9213_contactpic.png"
do {
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let documentDirectory = URL(fileURLWithPath: path)
let originPath = documentDirectory.appendingPathComponent(oldpicname)
let destinationPath = documentDirectory.appendingPathComponent(newpicname)
// -- here, note the change
let results = try FileManager.default.replaceItemAt(destinationPath, withItemAt: originPath)
print("----> results: \(results)")
} catch {
print("FIRST TRY FAILED TO RENAME FILE")
print(error)
}
}