iOS文件处理介绍(一)

来源:互联网 发布:农村淘宝面试技巧 编辑:程序博客网 时间:2024/06/07 07:09

iOS文件处理介绍(一)


一、在Documents、tmp和Library中存储文件
[摘要]本文介绍iOS文件处理,包括在Documents、tmp和Library中存储文件和读取、写入文件,并提供简单的示例代码供参考。

Documents:用于存储应用程序中经常需要读取或写入的常规文件。

tmp:用于存储应用程序运行时生成的文件。(随着应用程序的关闭失去了利用价值)

Library:一般存放应用程序的配置文件,比如说plist类型的文件。

二、读取和写入文件

1、新建Empty Application应用程序,添加HomeViewController文件。

HomeViewController.h代码:

View Row Code
1#import <UIKit/UIKit.h>23@interfaceHomeViewController : UIViewController4{56}7- (NSString*) documentsPath;//负责获取Documents文件夹的位置8- (NSString*)readFromFile:(NSString*)filepath;//读取文件内容9- (void)writeToFile:(NSString*)textwithFileName:(NSString*)filePath;//将内容写到指定的文件10@end

HomeViewController.m代码:

View Row Code
1#import"HomeViewController.h"2@interfaceHomeViewController ()3@end4@implementationHomeViewController5//负责获取Documents文件夹的位置6- (NSString*)documentsPath{7NSArray*paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);8NSString*documentsdir=[pathsobjectAtIndex:0];9return documentsdir;10}111213//读取文件内容14- (NSString*)readFromFile:(NSString*)filepath{15if ([[NSFileManagerdefaultManager]fileExistsAtPath:filepath]){16NSArray*content=[[NSArrayalloc]initWithContentsOfFile:filepath];17NSString*data=[[NSStringalloc]initWithFormat:@"%@",[contentobjectAtIndex:0]];18[contentrelease];19return data;20} else {21returnnil;22}23}24//将内容写到指定的文件25- (void)writeToFile:(NSString*)textwithFileName:(NSString*)filePath{26NSMutableArray*array=[[NSMutableArrayalloc]init];27[arrayaddObject:text];28[arraywriteToFile:filePath atomically:YES];29[arrayrelease];30}313233-(NSString*)tempPath{34returnNSTemporaryDirectory();35}36- (void)viewDidLoad37{38NSString*fileName=[[selfdocumentsPath]stringByAppendingPathComponent:@"content.txt"];3940//NSString *fileName = [[self tempPath] stringByAppendingPathComponent:@"content.txt"];4142[selfwriteToFile:@"苹果的魅力!"withFileName:fileName];4344NSString*fileContent=[selfreadFromFile:fileName];4546NSLog(fileContent);4748[superviewDidLoad];49}50@end

效果图:

iOS文件处理 - 1

iOS文件处理 - 2

0 0