xcode 如何重命名 Documents 目录中的文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15682202/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 03:05:13  来源:igfitidea点击:

How to rename files from Documents directory?

iphoneiosobjective-cxcode

提问by Nubaslon

I am saving my files in Document directory named 1.png, 2.png, 3.png, 4.png, 5.png. If I delete the original file 3.png, how do I rename files 4.pngand 5.pngto be called 3.pngand 4.pngrespectively?

我将文件保存在名为1.png, 2.png, 3.png, 4.png, 的Document 目录中5.png。如果我删除原始文件3.png,我怎么重命名文件4.png5.png被调用3.png,并4.png分别?

This is the code I am using to write the files in the first place:

这是我首先用来编写文件的代码:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                     NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
[appDel.photo addObject:@"photo"];
NSString *imageName = [NSString stringWithFormat:@"%i.png", [appDel.photo count]];
appDel.numberPhoto = [appDel.photo count];
NSString* path = [documentsDirectory stringByAppendingPathComponent:
                  imageName];
NSData* data = UIImagePNGRepresentation(image); 
[data writeToFile:path atomically:YES];

采纳答案by B.S.

To get NSDocumentsdirectory use :

获取NSDocuments目录使用:

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];

    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"MyFile.txt"];

How to rename file you can find here:

如何重命名文件,您可以在这里找到:

How to rename a file using NSFileManager

如何使用 NSFileManager 重命名文件

If you do not know the names of the files in documents directory you can use :

如果您不知道文档目录中文件的名称,您可以使用:

NSArray *directoryContent = [fileManager contentsOfDirectoryAtPath:documentsDirectory error:nil];

This array contains all filenames you need. So you can rename them all.

此数组包含您需要的所有文件名。所以你可以重命名它们。