OC对文本的操作

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        //创建文件
        NSString *homePath = NSHomeDirectory();
        //创建一个文件file.text
        NSString *filePath = [homePath stringByAppendingPathComponent:@"Documents/file.text"];
        //NSFileManager是单利模式,所以不能使用alloc+init创建
        NSFileManager *manager = [NSFileManager defaultManager];
        NSString *str = @"啦啦啦啦啦啦";
        NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
        //参数:文件路径、文件内容、文件的属性
        BOOL sucess = [manager createFileAtPath:filePath contents:data attributes:nil];
        if(sucess){
            NSLog(@"文件创建成功");
        }else{
            NSLog(@"文件创建失败");
        }
        //创建文件夹
        NSString *filePaths = [homePath stringByAppendingPathComponent:@"Documents/file"];
        NSError *error;
        //需要传递一个创建失败的指针对象,记录创建失败的信息
        BOOL success1 = [manager createDirectoryAtPath:filePaths withIntermediateDirectories:YES attributes:nil error:&error];
        if(!success1){
            NSLog(@"创建失败");
        }else{
            NSLog(@"创建成功");
        }
        //--------------------读取文件
        //根据路径读取文件内容
        NSData *datas = [manager contentsAtPath:filePath];
        NSString *s = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"%@",s);
        //--------------------移动文件/剪切文件
        //NSFileManager中没有提供重命名的方法,所以我们可以借助移动的api进行操作
        //把filePath移动到targetPath目录中
//        NSString *targetPath = [homePath stringByAppendingPathComponent:@"Documents/file/file2.text"];
//        BOOL sucess2 = [manager moveItemAtPath:filePath toPath:targetPath error:nil];
//        if(sucess2) {
//            NSLog(@"移动成功");
//        }else{
//            NSLog(@"移动失败");
//        }
        
        //这里有两个参数:一个是需要移动文件的路径,和需要移动到哪的路径
        //--------------------复制文件
//        BOOL sucess3 = [manager copyItemAtPath:filePath toPath:targetPath error:nil];
//        if(sucess3){
//            NSLog(@"复制成功");
//        }else{
//            NSLog(@"复制失败");
//        }
//        //--------------------删除文件
//        //删除之前需要判断这个文件是否存在
//        BOOL isExist = [manager fileExistsAtPath:filePath];//判断文件是否存在
//        if(isExist){
//            BOOL sucess4 = [manager removeItemAtPath:filePath error:nil];
//            if(sucess4){
//                NSLog(@"删除成功");
//            }else{
//                NSLog(@"删除失败");
//            }
//        }
//        //--------------------获取文件的属性
//        NSDictionary *dic = [manager attributesOfItemAtPath:filePath error:nil];
//        NSLog(@"%@",dic);//通过打印我们就可以查看文件属性的一些key属性一般是NSDictionary
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值