转自:http://blog.youkuaiyun.com/java886o/article/details/9041547
FileTools.h
FileTools.m
#import "FileTools.h"
@implementation FileTools
//复制文件
+ (void) copyFileWithSrcFile:(NSString*) srcFilePath withBakFile:(NSString*) bakFilePath {
//1.利用NSFileManager复制文件
//NSFileManager* manager = [NSFileManager defaultManager];
//[manager copyItemAtPath:srcFilePath toPath:bakFilePath error:nil];
//2.利用读原文件,写新文件复制文件
NSFileManager* fileManager = [NSFileManager defaultManager];
//创建新文件
BOOL createResult = [fileManager createFileAtPath:bakFilePath contents:nil attributes:nil];
if (createResult) {
NSLog(@"文件创建成功...");
}else {
NSLog(@"文件创建失败...");
return;
}
NSFileHandle* inStream = [NSFileHandle fileHandleForReadingAtPath:srcFilePath];
//特别注意-----必须先创建文件再创建outStream,否则将出现拷贝文件大小为0的问题
NSFileHandle* outStream = [NSFileHandle fileHandleForWritingAtPath:bakFilePath];
//初始化变量
NSInteger readCount = 0;
NSInteger fileSize = [[self fileLengthWithFile:srcFilePath] intValue];
NSLog(@"复制的文件大小为:%ld",fileSize);
BOOL isCanRead = YES;
NSData* bufferData = nil;
while(isCanRead) { //如果可以读文件,则开始读文件
[inStream seekToFileOffset:readCount];
if ((fileSize - readCount) < (1024 * 8)) { //如果剩下可读的文件小于8K,则直接读取到文件末尾,并保存文件,然后结束读取文件
bufferData = [inStream readDataToEndOfFile];
isCanRead = false;
[outStream writeData:bufferData];
break;
}else { //如果剩余的刻度文件大于等于8K,则跳转到已读文件位置,并读取8K的数据,保存文件,然后继续读取
bufferData = [inStream readDataOfLength:(1024 * 8)];
readCount+= (1024 * 8);
[outStream writeData:bufferData];
}
}
[outStream closeFile];
[inStream closeFile];
NSLog(@"文件拷贝完成...");
}
//获取文件大小
+ (NSNumber*) fileLengthWithFile:(NSString*) filePath {
NSFileManager* manager = [NSFileManager defaultManager];
NSDictionary* attrs = [manager attributesOfItemAtPath:filePath error:nil];
return [attrs objectForKey:NSFileSize];
}
@end
测试 main.m
-
-
- #import <Foundation/Foundation.h>
- #import "FileTools.h"
- int main(int argc, const char * argv[])
- {
- @autoreleasepool {
- NSNumber* size = [FileTools fileLengthWithFile:@"/Users/3g2win/Downloads/ios_development.cer"];
- NSLog(@"文件大小:%d",[size intValue]);
- [FileTools copyFileWithSrcFile:@"/Users/3g2win/Downloads/ios_development.cer" withBakFile:@"/Users/3g2win/Downloads/ios_development_备份.cer"];
- }
- return 0;
- }
-