9

我想从文档目录中抓取一个文件到一个NSData对象中,但如果我这样做,我NSData总是NIL

filepath = [[NSString alloc] init];
filepath = [self.GetDocumentDirectory stringByAppendingPathComponent:fileNameUpload];
NSData *data = [[NSFileManager defaultManager] contentsAtPath:filepath];

-(NSString *)GetDocumentDirectory{
fileMgr = [NSFileManager defaultManager];
homeDir = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];

return homeDir;

}

在这一点上,我总是得到一个例外,我的数据是NIL

[request addRequestHeader:@"Md5Hash" value:[data MD5]];

我检查了,没有文件,但我不知道为什么!我之前创建了该文件:

NSMutableString *xml = [[NSMutableString alloc] initWithString:[xmlWriter toString]];

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

//make a file name to write the data to using the documents directory:
NSMutableString *fileName = [NSMutableString stringWithFormat:@"%@/7-speed-",
                      documentsDirectory];

[xml writeToFile:fileName
          atomically:NO
            encoding:NSStringEncodingConversionAllowLossy
               error:nil];

通过以下方式解决了它:

[xml writeToFile:fileName
          atomically:YES
            encoding:NSUTF8StringEncoding
               error:nil];
4

2 回答 2

21

检查文件是否存在:

if([[NSFileManager defaultManager] fileExistsAtPath:filepath)
{
   NSData *data = [[NSFileManager defaultManager] contentsAtPath:filepath];
}
else
{
   NSLog(@"File not exits");
}
于 2012-11-05T10:36:52.757 回答
3

斯威夫特 3 版本

let filePath = fileURL.path
if FileManager.default.fileExists(atPath: filePath) {
    if let fileData = FileManager.default.contents(atPath: filePath) {
        // process the file data
    } else {
        print("Could not parse the file")
    }
} else {
    print("File not exists")
}
于 2016-11-02T07:20:53.650 回答