有没有一种好方法可以使用目标 c 在 Mac OS 中每个块复制一些文件或目录(带有文件和子目录)块?
问问题
926 次
2 回答
2
您可以通过创建 aNSInputStream
和 aNSOutputStream
并将它们安排在 a 中来为每个块复制一个文件NSRunLoop
。然后,当您从输入流中获取字节时,将它们写入缓冲区,当输出流准备好时,您将缓冲区的内容复制到其中。
@synthesize numberOfBytesTransferred = _numberOfBytesTransferred;
static const NSUInteger blockSize = 65536; // should be adjusted
- (void)startWithSourcePath:(NSString *)srcPath
destinationPath:(NSString *)dstPath
completionHandler:(void (^)(NSUInteger, NSError *))completionHandler
{
_buffer = malloc(blockSize);
_numberOfBytesTransferred = _bufferLength = _bufferOffset = 0;
_completionHandler = [completionHandler copy];
_srcStream = [[NSInputStream alloc] initWithFileAtPath:srcPath];
_dstStream = [[NSOutputStream alloc] initToFileAtPath:dstPath append:NO];
_srcStream.delegate = self;
_dstStream.delegate = self;
[_srcStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
[_dstStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
[_srcStream open];
[_dstStream open];
}
- (void)processStreams
{
if ( _srcStream.hasBytesAvailable && ! _bufferLength )
_bufferLength = [_srcStream read:_buffer maxLength:blockSize];
if ( _dstStream.hasSpaceAvailable && _bufferLength ) {
NSInteger length = [_dstStream write:_buffer + _bufferOffset maxLength:_bufferLength];
_bufferOffset += length;
_bufferLength -= length;
}
if ( _bufferOffset && !_bufferLength ) {
[self willChangeValueForKey:@"numberOfBytesTransferred"];
_numberOfBytesTransferred += _bufferOffset;
_bufferOffset = 0;
[self didChangeValueForKey:@"numberOfBytesTransferred"];
}
if ( _dstStream.hasSpaceAvailable && NSStreamStatusAtEnd == _srcStream.streamStatus ) {
[_srcStream close];
[_dstStream close];
_completionHandler(_numberOfBytesTransferred, nil);
}
}
- (void)cancel
{
[_srcStream close];
[_dstStream close];
}
- (void)pause
{
_paused = YES;
}
- (void)resume
{
_paused = NO;
[self processStreams];
}
- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode
{
if ( NSStreamEventErrorOccurred == eventCode ) {
[_srcStream close];
[_dstStream close];
_completionHandler(_numberOfBytesTransferred, stream.streamError);
return;
}
if ( ! _paused )
[self processStreams];
}
复制目录的内容需要枚举目录的内容。您可以创建一个NSDirectoryEnumerator
with的实例-[NSFileManager enumeratorAtPath:]
。
一旦你有了枚举器,你调用nextObject
然后获取文件属性:
- 如果文件是目录,则在目标目录中创建一个新目录
- If the file is a regular file, you start a file copy task and wait until the completion handler is called.
于 2011-12-23T21:09:19.247 回答
0
您可以使用 复制文件或目录-[NSFileManager copyItemAtPath:toPath:error:]
。
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *srcPath = @"/Users/nicolas/Documents/Xcode projects";
NSString *dstPath = @"/Users/nicolas/Desktop/Backup/Xcode projects";
NSError *error;
if ( ! [fileManager copyItemAtPath:srcPath toPath:dstPath error:&error] )
NSLog(@"Copy error: %@", error);
于 2011-12-23T12:48:24.830 回答