OC之文件管理写入文件
来源:互联网 发布:饥荒联机百科全书软件 编辑:程序博客网 时间:2024/05/11 12:25
//// WriteDate.m// NSFIleHandleTask1//// Created by New-World on 13-11-3.// Copyright (c) 2013年 Gary. All rights reserved.//#import "WriteDate.h"@implementation WriteDate-(void)runWrite{ NSFileManager *fileManger=[NSFileManager defaultManager]; NSString *path=NSHomeDirectory(); NSString *filepath=[path stringByAppendingPathComponent:@"Date.text"];//文件路径 BOOL success =[fileManger createFileAtPath:filepath contents:nil attributes:nil]; if (success) { NSLog(@"Date文件创建成功"); } NSFileHandle *fileHandle=[NSFileHandle fileHandleForWritingAtPath:filepath];//创建一个写入数据的fileHandle对象 NSTimer * timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction:) userInfo:fileHandle repeats:YES];//创建一个timer对象,每隔一秒钟写入一条数据 [timer fire];//启动timer}-(void)timerAction:(NSTimer *)timer{ static int n=0; NSFileHandle *fileHandle=timer.userInfo; [fileHandle seekToEndOfFile];//设置文件偏移量到文件末尾 NSDate *nowDate=[NSDate date];//获取系统时间 NSDateFormatter *dateformate=[[NSDateFormatter alloc] init];//建立时间格式对象 [dateformate setDateFormat:@"yyyy/MM/dd HH/mm/ss"]; NSString *datestring=[dateformate stringFromDate:nowDate];//按格式字符串格式化获取的时间 NSLog(@"%@",datestring); datestring=[datestring stringByAppendingString:@"\n"];//添加一个换行符 NSData *data=[datestring dataUsingEncoding:NSUTF8StringEncoding]; [fileHandle writeData:data]; if (n==10) { [timer invalidate];//设置timer无效 [fileHandle closeFile];//关闭fileHandle } n++; }@end