将nsdata写入特定位置的文件中

时间:2014-06-18 13:24:36

标签: ios file-io nsdata writetofile

我有以下代码用于在文件中写入数据:

NSData *chunk=...; //some data
 NSArray *docDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docDirectory = [docDirectories objectAtIndex:0];
    NSString *fileName   = [docDirectory stringByAppendingPathComponent:@"TestFile.txt"];
 [chunk writeToFile:fileName atomically:NO];

如果我知道文件的大小(让我们说10 *块)并且如果我还在文件的总长度中接收每个块的位置,我该如何在该特定位置添加写入数据到文件?

1 个答案:

答案 0 :(得分:1)

要解决您的问题,最好的办法是使用NSOutputStream,这样可以更轻松地处理这些操作。

话虽如此,你会像这样附加到文件的末尾:

NSOutputStream *stream = [[NSOutputStream alloc] initToFileAtPath:filePath append:YES];
[stream open];
NSData *chunk = ...; // some data
[stream write:(uint8_t *)[chunk bytes] maxLength:[chunk length]];
[stream close];
// remember to always handle memory (if not using ARC) //

要在文件中间插入一大块数据,需要更多参与:

NSData *chunk = ...; // some data
NSString *filePath = ... ; // get the file //
NSUInteger insertionPoint = ...; // get the insertion point //
// make sure the file exists, if it does, do the following //
NSData *oldData = [NSData dataWithContentsOfFile:filePath];
// error checking would be nice... if (oldData) ... blah //
NSOutputStream *stream = [[NSOutputStream alloc] initToFileAtPath:filePath append:NO];
[stream open];
[stream write:(uint8_t *)[oldData bytes] maxLength:insertionPoint]; // write the old data up to the insertion point //
[stream write:(uint8_t *)[chunk bytes] maxLength:[chunk length]]; // write the new data //
[stream write:(uint8_t *)&[oldData bytes][insertionPoint] maxLength:[oldData length] - insertionPoint]; // write the rest of old data at the end of the file //
[stream close];
// remember to always handle memory (if not using ARC) //

免责声明:用浏览器编写的代码。