zoukankan      html  css  js  c++  java
  • iOS文件处理介绍(一)

    一、在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

    效果图:

    iOS文件处理 - 1

    iOS文件处理 - 2

     

     

     

    本文转载至 http://mobile.9sssd.com/ios/art/953

  • 相关阅读:
    4412开发板Android教程——Android平台简介
    CF621E Wet Shark and Blocks(矩阵加速DP)
    CF963B Destruction of a Tree(高级DFS)
    CF474E Pillars(离散化+线段树+保存DP路径)
    CF1214E Petya and Construction Set(树上构造)
    CF360B Levko and Array(DP+二分答案)
    CF1060E Sergey and Subway(公式推导+树上信息统计)
    CF641E Little Artem and Time Machine(时间离散化+平衡树套树状数组)
    CF264C Choosing Balls(保留最大值、次大值+DP)
    CF571B. Minimization(DP)
  • 原文地址:https://www.cnblogs.com/Camier-myNiuer/p/3168964.html
Copyright © 2011-2022 走看看