首先要區分兩個類:NSFileManager 主要負責對檔案本身的操作(刪除、修改、移動、複製等);NSFileHandle 則主要負責對檔案內容進行讀取與寫入。
值得一提的是,借助 NSFileHandle 還可以實現斷點續傳。
NSString *homePath = NSHomeDirectory(); NSString *filePath = [homePath stringByAppendingPathComponent:@"Desktop/hello.rtf"]; NSFileHandle *fileHandle = [NSFileHandle fileHandleForReadingAtPath:filePath]; NSUInteger length = [fileHandle availableData].length; [fileHandle seekToFileOffset:length/2]; NSData *data = [fileHandle readDataToEndOfFile]; NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"%@",str);
NSString *homePath = NSHomeDirectory(); NSString *filePath = [homePath stringByAppendingPathComponent:@"Desktop/hello.rtf"]; NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:filePath]; // [fileHandle seekToEndOfFile]; [fileHandle seekToFileOffset:10]; NSString *str = @"data"; NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding]; [fileHandle writeData:data]; [fileHandle closeFile]; NSLog(@"Hello, World!");
NSString *homePath = NSHomeDirectory(); NSString *filePath = [homePath stringByAppendingPathComponent:@"Desktop/hello.rtf"]; NSString *objPath = [homePath stringByAppendingPathComponent:@"Desktop/copy.rtf"]; NSFileManager *fileManager = [NSFileManager defaultManager]; BOOL success = [fileManager createFileAtPath:objPath contents:nil attributes:nil]; NSFileHandle *writeFile = [NSFileHandle fileHandleForReadingAtPath:filePath]; NSFileHandle *objFile = [NSFileHandle fileHandleForWritingAtPath:objPath]; [objFile readDataToEndOfFile]; NSData *data = [writeFile readDataToEndOfFile]; [objFile writeData:data]; [writeFile closeFile]; [objFile closeFile];