OC之文件管理写入文件

//
//  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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值