NSURL故障导致NSFileHandle [英] NSFileHandle from NSURL failure
问题描述
我正在尝试将一些数据写入文件.我可以从文件对话框中获取NSURL,并且获得的NSURL具有以下值
I'm trying to write some data to a file. I am able to obtain an NSURL from a file dialog and the NSURL obtained has the following value
file:///Users/brad/Documents/2016-05-04-06-53-35.csv
我的代码执行以下操作:
My code does the following:
NSURL* myFile = [panel URL]; // is file:///Users/brad/Documents/2016-05-04-06-53-35.csv
NSError *error = nil;
NSFileHandle *myFileHandle = [NSFileHandle fileHandleForWritingToURL:myFile error:&error];
NSLog(@"%@",error);
if (myFileHandle)
{
... // do something
}
else
{
NSLog(@"File operation failed");
}
我收到一条错误消息,指出以下内容
I get an error which indicates the following
Error Domain=NSCocoaErrorDomain Code=2 "(null)" UserInfo={NSFilePath=/Users/brad/Documents/
myFileHandle也为零.
Also myFileHandle is nil.
有任何线索吗?
推荐答案
请参见NSFileHandle fileHandleForWritingToURL:error:
的文档.如果文件不存在,您将返回nil
.
See the documentation for NSFileHandle fileHandleForWritingToURL:error:
. You get back nil
if the file doesn't already exist.
使用NSFileManager
首先检查文件是否存在.如果不是,请使用NSFileManager createFileAtPath:contents:attributes:
创建一个空文件.
Use NSFileManager
to first check if the file exists or not. If not, use NSFileManager createFileAtPath:contents:attributes:
to create an empty file.
NSURL *myFile = [panel URL];
if (![[NSFileManager defaultManager] fileExistsAtPath:[myFile path]]) {
[[NSFileManager defaultManager] createFileAtPath:[myFile path] contents:[NSData data] attributes:nil];
}
NSError *error = nil;
NSFileHandle *myFileHandle = [NSFileHandle fileHandleForWritingToURL:myFile error:&error];
这篇关于NSURL故障导致NSFileHandle的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!