- (IBAction)copyFile
{
//source file : source.txt ==> source copy.txt
NSString *documentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
NSString *sourceFilePath = [documentsPath stringByAppendingPathComponent:@"source.txt"];
NSLog(@"source:%@", sourceFilePath);
NSString *fileExtension = [sourceFilePath pathExtension];
NSString *fileName = [sourceFilePath stringByDeletingPathExtension];
// xxxx.txt xxxx copy.txt
NSString *targetFilePath = [[fileName stringByAppendingString:@" copy"]stringByAppendingPathExtension:fileExtension];
NSLog(@"targetFilePath:%@", targetFilePath);
//读handle
NSFileHandle *sourceFileHandle = [NSFileHandle fileHandleForReadingAtPath:sourceFilePath];
[[NSFileManager defaultManager]createFileAtPath:targetFilePath contents:nil attributes:nil];
//写handle
NSFileHandle *targetFileHandle = [NSFileHandle fileHandleForWritingAtPath:targetFilePath];
//拷贝数据
#define MAX_SIZE 10
unsigned long long size = [sourceFileHandle seekToEndOfFile];//35
[sourceFileHandle seekToFileOffset:0];
unsigned long long offset = 0;
NSData *data = nil;
while(offset <= size){
data = [sourceFileHandle readDataOfLength:MAX_SIZE];
[targetFileHandle writeData:data];
offset += MAX_SIZE;
}
[sourceFileHandle closeFile];
[targetFileHandle closeFile];
}
- (IBAction)combine
{
NSString *documentsPath = [NSHomeDirectory()stringByAppendingPathComponent:@"Documents"];
//获取到Documents下的所有文件
NSArray *files = [[NSFileManager defaultManager]contentsOfDirectoryAtPath:documentsPath error:nil];
//过滤非txt文件
NSMutableArray *txtfiles = [[NSMutableArray alloc]init];
for (NSString *file in files) {
if([[file pathExtension] isEqualToString:@"txt"]){
[txtfiles addObject:file];
}
}
//创建合并文件
NSString *combineFilePath = [documentsPath stringByAppendingPathComponent:@"combine.txt"];
[[NSFileManager defaultManager]createFileAtPath:combineFilePath contents:nil attributes:nil];
//创建handle
NSFileHandle *writingHandle = [NSFileHandle fileHandleForWritingAtPath:combineFilePath];
//拷贝多件内容到合并文件
for (NSString *fileName in txtfiles)
{
NSString *filePath = [documentsPath stringByAppendingPathComponent:fileName];
NSFileHandle *readingHandle = [NSFileHandle fileHandleForReadingAtPath:filePath];
NSData *data = [readingHandle readDataToEndOfFile];
[readingHandle closeFile];
[writingHandle writeData:data];
}
[writingHandle closeFile];
}