//
// main.m
// NSFIleHandleTask2
//
// Created by New-World on 13-11-3.
// Copyright (c) 2013年 Gary. All rights reserved.
//
#import <Foundation/Foundation.h>
#define Max 5000 //每次读取文件的大小
int main(int argc, const char * argv[])
{
@autoreleasepool {
#pragma mark 创建文件
NSString *homepath=NSHomeDirectory();
NSString *targetPath=[homepath stringByAppendingPathComponent:@"Objective-C_Recipes_bak.pdf"];//需要写入的文件的路
NSFileManager *filemanager=[NSFileManager defaultManager];
BOOL isSuccess=[filemanager createFileAtPath:targetPath contents:nil attributes:nil];
if(isSuccess)
{
NSLog(@"创建文件成功!");
}
NSString *scrPath=[homepath stringByAppendingPathComponent:@"Objective-C_Recipes.pdf"];//需要读取的文件的路径
NSFileHandle *inFile=[NSFileHandle fileHandleForReadingAtPath:scrPath];
NSFileHandle *outFile=[NSFileHandle fileHandleForWritingAtPath:targetPath];
#pragma mark 获取文件大小
NSError *error= nil;
NSDictionary *fileAttr=[filemanager attributesOfItemAtPath:scrPath error:&error];
if(nil!=error){
NSString *str=[error localizedDescription];
NSLog(@"错误:%@",str);
}
//获取文件的属性值
NSNumber *fileSizeNum=[fileAttr objectForKey:NSFileSize];
NSInteger fileSize=[fileSizeNum longValue];//文件的大小
#pragma mark 写入文件
NSInteger readSize=0;
BOOL isEnd =YES;
NSAutoreleasePool *p=nil;//定义一个自动释放池
int n=0;//进行读取计数
while (isEnd) {
if(n%10==0)//每十次释放一次内存
{
[p release];
p = [[NSAutoreleasePool alloc]init];
}
NSInteger subLength=fileSize-readSize;
NSData *data=nil;
if (subLength<Max) {
isEnd =NO;//表示已经到文件结尾,要退出循环
[inFile readDataToEndOfFile];//读取到文件末尾
}
else
{
data=[inFile readDataOfLength:Max];
readSize+=Max;
[inFile seekToFileOffset:readSize];//设置文件偏移量
}
[outFile writeData:data];//向新创建的文件写入数据
n++;
}
NSLog(@"文件复制成功!");
[inFile closeFile];
[outFile closeFile];//关闭文件流
}
return 0;
}
OC之文件管理复制文件
最新推荐文章于 2022-05-31 21:34:31 发布