一、在Documents、tmp和Library中存储文件
Documents:用于存储应用程序中经常需要读取或写入的常规文件。
tmp:用于存储应用程序运行时生成的文件。(随着应用程序的关闭失去了利用价值)
Library:一般存放应用程序的配置文件,比如说plist类型的文件。
二、读取和写入文件
1、新建Empty Application应用程序,添加HomeViewController文件。
HomeViewController.h代码:
1 | #import <UIKit/UIKit.h> |
2 | |
3 | @interface HomeViewController : UIViewController |
4 | { |
5 | |
6 | } |
7 | - (NSString *) documentsPath;//负责获取Documents文件夹的位置 |
8 | - (NSString *) readFromFile:(NSString *)filepath; //读取文件内容 |
9 | - (void) writeToFile:(NSString *)text withFileName:(NSString *)filePath;//将内容写到指定的文件 |
10 | @end |
HomeViewController.m代码:
1 | #import "HomeViewController.h" |
2 | @interface HomeViewController () |
3 | @end |
4 | @implementation HomeViewController |
5 | //负责获取Documents文件夹的位置 |
6 | - (NSString *) documentsPath{ |
7 | NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); |
8 | NSString *documentsdir = [paths objectAtIndex:0]; |
9 | return documentsdir; |
10 | } |
11 | |
12 | |
13 | //读取文件内容 |
14 | - (NSString *) readFromFile:(NSString *)filepath{ |
15 | if ([[NSFileManager defaultManager] fileExistsAtPath:filepath]){ |
16 | NSArray *content = [[NSArray alloc] initWithContentsOfFile:filepath]; |
17 | NSString *data = [[NSString alloc] initWithFormat:@"%@", [content objectAtIndex:0]]; |
18 | [content release]; |
19 | return data; |
20 | } else { |
21 | return nil; |
22 | } |
23 | } |
24 | //将内容写到指定的文件 |
25 | - (void) writeToFile:(NSString *)text withFileName:(NSString *)filePath{ |
26 | NSMutableArray *array = [[NSMutableArray alloc] init]; |
27 | [array addObject:text]; |
28 | [array writeToFile:filePath atomically:YES]; |
29 | [array release]; |
30 | } |
31 | |
32 | |
33 | -(NSString *)tempPath{ |
34 | return NSTemporaryDirectory(); |
35 | } |
36 | - (void)viewDidLoad |
37 | { |
38 | NSString *fileName = [[self documentsPath] stringByAppendingPathComponent:@"content.txt"]; |
39 | |
40 | //NSString *fileName = [[self tempPath] stringByAppendingPathComponent:@"content.txt"]; |
41 | |
42 | [self writeToFile:@"苹果的魅力!" withFileName:fileName]; |
43 | |
44 | NSString *fileContent = [self readFromFile:fileName]; |
45 | |
46 | NSLog(fileContent); |
47 | |
48 | [super viewDidLoad]; |
49 | } |
50 | @end |
效果图:
本文转载至 http://mobile.9sssd.com/ios/art/953