将文件复制到不同目录

发布于 2024-12-22 23:54:38 字数 563 浏览 3 评论 0原文

假设我在路径 /documents/recording.caf 中有一个文件,我想将其复制到文件夹 /documents/folder 中。我该怎么做?如果我想使用以下代码,似乎我必须在路径中包含文件名和扩展名,而我并不总是知道这些。

NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *newPath = [documentsDirectory stringByAppendingPathComponent:@"/temporary/recording.caf"];

if ([fileManager fileExistsAtPath:newPath] == NO) {

    [fileManager copyItemAtPath:file toPath:newPath error:&error];

    }

}

表格视图会使用它在目录中找到的每个文件进行更新,如果用户点击一个单元格,我想将该文件复制到其他地方。

Let's say I have a file at the path /documents/recording.caf and I want to copy it into the folder /documents/folder. How would I do this? If I want to use the following code, it appears as though I have to include the file name and extension in the path, which I will not always know.

NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *newPath = [documentsDirectory stringByAppendingPathComponent:@"/temporary/recording.caf"];

if ([fileManager fileExistsAtPath:newPath] == NO) {

    [fileManager copyItemAtPath:file toPath:newPath error:&error];

    }

}

A tableview is updated with every file it finds in a directory and if the user taps a cell, I want to copy this file somewhere else.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

宫墨修音 2024-12-29 23:54:38

由于附加的路径组件也是一个字符串,因此您可以使用另一个命令创建另一个带有您不知道的文件名的字符串

NSString *anotherString=[NSString stringWithFormat:@"/temporary/%@",<yourfilenameAsString>];

,然后将其附加到 newPath 中。

我还建议您不要构建像 @"/temporary/filename.extension" 这样的路径。相反,您可以使用 NSString 的路径构造方法来构造它,例如

- (NSString *)stringByAppendingPathComponent:(NSString *)aString
- (NSString *)stringByAppendingPathExtension:(NSString *)ext

Since the appended path component is also a string, you could use another create another string with the file name that you do not know

NSString *anotherString=[NSString stringWithFormat:@"/temporary/%@",<yourfilenameAsString>];

and just append that to newPath.

I would also suggest that you should not be constructing paths like @"/temporary/filename.extension". But rather, you construct it as using the path construction methods of NSString like

- (NSString *)stringByAppendingPathComponent:(NSString *)aString
- (NSString *)stringByAppendingPathExtension:(NSString *)ext
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文