zoukankan      html  css  js  c++  java
  • ios文件处理(一)

    一.在Documents、tmp和Library中存储文件

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

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

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

    二.读取和写入文件

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

     HomeViewController.h代码:

     #import <UIKit/UIKit.h>

    @interface HomeViewController : UIViewController
    {
        
    }
    - (NSString *) documentsPath;//负责获取Documents文件夹的位置
    - (NSString *) readFromFile:(NSString *)filepath; //读取文件内容
    - (void) writeToFile:(NSString *)text withFileName:(NSString *)filePath;//将内容写到指定的文件
    @end

     HomeViewController.m代码: 

    #import "HomeViewController.h"
    @interface HomeViewController ()
    @end
    @implementation HomeViewController
    //负责获取Documents文件夹的位置
    - (NSString *) documentsPath{
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsdir = [paths objectAtIndex:0];
        return documentsdir;
    }
    //读取文件内容 
    - (NSString *) readFromFile:(NSString *)filepath{
        if ([[NSFileManager defaultManager] fileExistsAtPath:filepath]){
            NSArray *content = [[NSArray alloc] initWithContentsOfFile:filepath]; 
            NSString *data = [[NSString alloc] initWithFormat:@"%@", [content objectAtIndex:0]];
            [content release];
            return data;
        } else {
            return nil;
        }
    }
    //将内容写到指定的文件
    - (void) writeToFile:(NSString *)text withFileName:(NSString *)filePath{
        NSMutableArray *array = [[NSMutableArray alloc] init];
        [array addObject:text];
        [array writeToFile:filePath atomically:YES];
        [array release];
    }
    -(NSString *)tempPath{
        return NSTemporaryDirectory();
    }
    - (void)viewDidLoad
    {
        NSString *fileName = [[self documentsPath] stringByAppendingPathComponent:@"content.txt"];
        
        //NSString *fileName = [[self tempPath] stringByAppendingPathComponent:@"content.txt"];
        
        [self writeToFile:@"苹果的魅力!" withFileName:fileName];
        
        NSString *fileContent = [self readFromFile:fileName];
        
        NSLog(fileContent);
        
        [super viewDidLoad];
    }
    @end
    效果图: 

     

     

  • 相关阅读:
    shell脚本从文件夹中递归提取文件
    php生成图片缩略图,支持png透明
    shell脚本批量下载资源并保留路径
    PHP字符串word末字符大小写互换
    编译gearman提示缺少boost
    Rebranding(模拟+思维)
    拼接平方数(枚举每个数的组合情况就好)----------蓝桥备战系列
    格子刷油漆(dp)-----------蓝桥备战系列
    高僧斗法(nim博弈)----------蓝桥备战系列
    网络寻路(思维+vector的应用)-----------蓝桥备战系列
  • 原文地址:https://www.cnblogs.com/hanjun/p/2743694.html
Copyright © 2011-2022 走看看