在Cocoa中重命名文件? [英] Rename file in Cocoa?

查看:135
本文介绍了在Cocoa中重命名文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何重命名文件,将文件保存在同一目录中?

How would I rename a file, keeping the file in the same directory?

我有一个包含文件完整路径的字符串,新的文件名(并且没有路径),例如:

I have a string containing a full path to a file, and a string containing a the new filename (and no path), for example:

NSString *old_filepath = @"/Volumes/blah/myfilewithrubbishname.avi";
NSString *new_filename = @"My Correctly Named File.avi";

我知道NSFileManager的 movePath:toPath:handler:方法,但我不能锻炼如何构造新文件的路径。

I know about NSFileManager's movePath:toPath:handler: method, but I cannot workout how to construct the new file's path..

基本上我正在寻找等效于以下Python代码:

Basically I'm looking for the equivalent to the following Python code:

>>> import os
>>> old_filepath = "/Volumes/blah/myfilewithrubbishname.avi"
>>> new_filename = "My Correctly Named File.avi"
>>> dirname = os.path.split(old_filepath)[0]
>>> new_filepath = os.path.join(dirname, new_filename)
>>> print new_filepath
/Volumes/blah/My Correctly Named File.avi
>>> os.rename(old_filepath, new_filepath)


推荐答案

NSFileManager和NSWorkspace都有文件操作方法,但NSFileManager的 - (BOOL)movePath:(NSString *)源toPath:(NSString *)目标处理程序:(id)处理程序 。使用NSString的路径处理方法来获取文件和文件夹名称。例如,

NSFileManager and NSWorkspace both have file manipulation methods, but NSFileManager's - (BOOL)movePath:(NSString *)source toPath:(NSString *)destination handler:(id)handler is probably your best bet. Use NSString's path manipulation methods to get the file and folder names right. For example,

NSString *newPath = [[oldPath stringByDeletingLastPathComponent] stringByAppendingPathComponent:newFilename];
[[NSFileManager defaultManager] movePath:oldPath toPath:newPath handler:nil];

这两个类在文档中解释得很好,但如果有什么你不理解。

Both classes are explained pretty well in the docs, but leave a comment if there's anything you don't understand.

这篇关于在Cocoa中重命名文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆