void test2(){ NSString *path = @"/Users/gx/Desktop/test_utf8.txt"; //NSString *str = [NSString stringWithContentsOfFile:path]; //UTF-8编码 NSString *str = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil]; NSLog(@"%@",str); //GBK编码 NSString *path2 = @"/Users/gx/Desktop/test_gbk.txt"; NSString *str2 = [NSString stringWithContentsOfFile:path2 encoding:CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000) error:nil]; NSLog(@"%@",str2); //使用NSURL从文件中读取字符串 NSURL *url = [NSURL URLWithString:@"file:///Users/gx/Desktop/test_utf8.txt"]; NSString *str3 = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil]; NSLog(@"%@",str3); //使用NSURL读取远程文本 NSURL *url2 = [NSURL URLWithString:@"http://www.baidu.com"]; NSString *str4 = [NSString stringWithContentsOfURL:url2 encoding:NSUTF8StringEncoding error:nil]; NSLog(@"%@",str4); }
//字符串的导出(写入到文件) void test3(){ NSString *str = @"123123123这是一个导出的字符串"; //文件不存在会自动创建,文件夹不存在则不会自动创建会报错 NSString *path = @"/Users/gx/Desktop/test_export.txt"; NSError *error; [str writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:&error]; if (error) { NSLog(@"导出失败:%@",error); }else{ NSLog(@"导出成功"); } }