文件操作
// file:///var/containers/Bundle/Application/4256C1D8-84BC-4F4C-A5A2-BCAAF8A83D2C/OTC_heartStick.app/pack_demo.txt
// url读取是以 file://开始的
NSURL *urlDemo = [[NSBundle mainBundle] URLForResource:@"pack_demo.txt" withExtension:nil];
// 没有中文情况下可以使用 直接转string类型数据
NSString *urlString = [urlDemo absoluteString];
NSLog(@"%@", urlString);
NSString *contentOne = [NSString stringWithContentsOfURL:urlDemo encoding:NSUTF8StringEncoding error:nil];
// 直接以/xxxx/xxx,,,,开始
NSString *path = [[NSBundle mainBundle] pathForResource:@"pack_demo.txt" ofType:nil];
// 获取内容
NSString *contenttwo = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
NSLog(@"%@---%@", contentOne, contenttwo);
// 返回路径的组成部分 <__NSArrayM 0x100956340>(
// /,
// var,
// containers,
// Bundle,
// Application,
// 0B43ABDC-17AA-4BA3-BF10-B0DC129A2D07,
// OTC_heartStick.app,
// pack_demo.txt
// )
NSArray *patharray = [path pathComponents];
NSLog(@"%@", patharray);
// 返回路径最后组成部分 txt
NSString *str = [path lastPathComponent];
// 这种方式有一点不好,就是需要添加/
[path stringByAppendingString:@"/appFile.text"];
// 不需要添加/
[path stringByAppendingPathComponent:@"appFile.text"];
// 删除最后的组成部分
str = [path stringByDeletingLastPathComponent];
// 删除扩展名(.text被删除了)
str = [path stringByDeletingPathExtension];
// 获取扩展名
str = [path pathExtension];
// 添加扩展名
[path stringByAppendingPathExtension:@".jpg"];
//存储是有编码方式的,编程字节码
//相当于Java中的解码和编码
NSString *s = @"tsdfsdfsdfsdf";
NSData *data = [s dataUsingEncoding:NSUTF8StringEncoding];
s = [[NSString alloc] initWithData:data encoding:(NSUTF8StringEncoding)];
//获取沙盒目录
NSString *homePath = NSHomeDirectory();
//在沙盒目录中创建一个文件file.text
NSString *filePath = [homePath stringByAppendingPathComponent:@"Documents/file.text"];
//NSFileManager是单利模式, 所以不能使用alloc+init创建
NSFileManager *manager = [NSFileManager defaultManager];
NSString *strone = @"无线互联";
NSData *dataone = [strone dataUsingEncoding:NSUTF8StringEncoding];
//参数:文件路径、文件内容、文件的属性
BOOL sucess = [manager createFileAtPath:filePath contents:dataone 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(@"创建失败");
}
NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSDictionary *fileAttr = [fileManager attributesOfItemAtPath:filePath error:nil];
NSNumber *fileSize = [fileAttr objectForKey:NSFileSize];
long long sizeValue = [fileSize longLongValue];
NSLog(@"%@--%lld", fileSize, sizeValue);
// 读取到文件后,使用特定支付分割
NSArray *arrayString = [contenttwo componentsSeparatedByString:@"\r\n"];
网友评论