使用 NSData 方法“writeToFile:atomically:”时如何保留文件名中的冒号字符?
当我运行以下代码时,写入磁盘的文件名最终如下所示:“MyFileName_2011-02-07_13/07/55.png”。我想保留冒号字符,而不是正斜杠。当我在控制台中 NSLog“fileName” 时,它看起来是正确的。我缺少什么?
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd_HH:mm:ss"];
NSString *dateString = [dateFormatter stringFromDate:[NSDate date]];
NSString *fileName = [NSString stringWithFormat:@"MyFileName_%@.png", dateString];
[myNSData writeToFile:fileName atomically:NO];
When I run the following code, the filename that gets written on the disk ends up like this: "MyFileName_2011-02-07_13/07/55.png". I'd like to keep the colon character, not forward slashes. When I NSLog "fileName" in console it looks right. What am I missing?
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd_HH:mm:ss"];
NSString *dateString = [dateFormatter stringFromDate:[NSDate date]];
NSString *fileName = [NSString stringWithFormat:@"MyFileName_%@.png", dateString];
[myNSData writeToFile:fileName atomically:NO];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
文件名确实包含冒号; Finder 将其替换为斜杠。
这是从不能使用冒号时遗留下来的,因为它是 Mac OS 上的路径分隔符。现在,路径分隔符是斜杠,因此是开关。
Finder 仍然不允许您输入冒号;如果您尝试输入斜杠,它会成功,但在保存名称时用冒号代替。
几乎在其他地方,包括在 Cocoa 中,冒号是有效的(不是路径分隔符),但斜杠不是。
The filename does contain the colon; the Finder replaces it with slashes.
This is a holdover from when you couldn't use a colon because it was the path separator on Mac OS. Now, the path separator is the slash, hence the switch.
The Finder still won't let you enter a colon; if you try to enter a slash, it'll succeed, but save the name with a colon in its place.
Pretty much everywhere else, including in Cocoa, a colon is valid (not a path separator) but a slash isn't.
在 Darwin(即 OS X 和 iOS)上,文件名中通常不可能包含
:
字符。只需尝试重命名 Mac 上的文件以包含:
。 writeToFile: 方法显然只是替换非法字符而不是产生错误。It is generally not possible to have the
:
character in filenames on Darwin (i.e. OS X and iOS). Just try to rename a file on your Mac to contain the:
. ThewriteToFile:
method apparently simply replaces illegal characters instead of producing and error.