文件管理:创建文件,读取内容,剪切文件

AppDelegate.m

/*
 在Documents下创建一个文件“mobile.text”,内容为“iPhone、android、windows phone”,
 然后我们再次读取内容,并将内容修改为“iPhone、windows phone、android”,
 并且将文件名称改为“cellPhone.text”。
 然后我们在根目录下创建一个文件夹名为“phone”,在将文件剪切到该目录下。
 */

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    
    NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/mobile.text"];
    //创建需要写入的内容
    NSString *s = @"iPhone、android、windows phone";
    
    //1.创建文件,写入内容
    BOOL success = [s writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:NULL];
    
    if (success) {
        NSLog(@"写入成功");
    }
    
    //2.读取内容,并且修改内容
    NSString *s2 = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:NULL];
    //将字符串转换成数组
    NSArray *arrary = [s2 componentsSeparatedByString:@"、"];
    //不可变数组转换成可变数组
    NSMutableArray *arrary2 = [NSMutableArray arrayWithArray:arrary];
    //将下标为1和2的元素交换
    [arrary2 exchangeObjectAtIndex:1 withObjectAtIndex:2];
    //将数组转换成字符串
    NSString *newString = [arrary2 componentsJoinedByString:@"、"];
    
//    [newString writeToFile:<#(NSString *)#> atomically:<#(BOOL)#> encoding:<#(NSStringEncoding)#> error:<#(NSError *__autoreleasing *)#>]

    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *newPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/cellPhone.text"];
    NSData *data = [newString dataUsingEncoding:NSUTF8StringEncoding];
    //创建文件
    [fileManager createFileAtPath:newPath contents:data attributes:nil];
    
    //3.在根目录下创建文件夹,并且剪切文件
    NSString *path2 = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/phone"];
    //创建文件夹
    [fileManager createDirectoryAtPath:path2 withIntermediateDirectories:YES attributes:nil error:nil];
    NSString *path3 = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/phone/cellPhone.text"];
    [fileManager moveItemAtPath:newPath toPath:path3 error:NULL];

    return YES;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值