• iOS 文件读写



    #import <Foundation/Foundation.h>
    
    @interface Utils : NSObject
    +(void) writeFile:(NSString *) filePath data:(NSString *) _data;
    +(NSString *) readFile:(NSString *) filePath;
    @end
    


    #import "Utils.h"
    
    @implementation Utils
    +(void) writeFile:(NSString *) filePath data:(NSString *) _data{
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString* fileName = [[paths objectAtIndex:0]stringByAppendingPathComponent:filePath];
        NSLog(@"File %@ will write!", fileName);
        
        // 用这个方法来判断当前的文件是否存在,如果不存在,就创建一个文件
        NSFileManager *fileManager = [NSFileManager defaultManager];
        if ( ![fileManager fileExistsAtPath:fileName]) {
            NSLog(@"File %@ not exists!", fileName);
            [fileManager createFileAtPath:fileName contents:nil attributes:nil];
        }else NSLog(@"File %@ exists!", fileName);
        
        
        [_data writeToFile:fileName atomically:YES encoding:NSUTF8StringEncoding error:NULL];
    }
    
    +(NSString *) readFile:(NSString *) filePath{
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString* fileName = [[paths objectAtIndex:0]stringByAppendingPathComponent:filePath];
        NSLog(@"File %@ will write!", fileName);
    
        NSString* myString = [NSString stringWithContentsOfFile:fileName usedEncoding:NULL error:NULL];
        return myString;
    }
    @end
    

    调用:

    [Utils writeFile:@"/Lein.txt" data:@"123QWE金属材料"];
        NSLog(@"Lein.txt:%@", [Utils readFile:@"/Lein.txt"]);




  • 相关阅读:
    吴太银:华为消费者云服务Cassandra使用场景与最佳实践
    使用FileZilla连接Linux
    debug 与 release
    删除cocos2dx项目模版
    [转]C/C++控制台输出时设置字体及背景颜色
    iphone调试的一些问题
    [转]Refactoring Game Entities with Components
    使用QT + cocos2dx制作工具
    [转]printf输出字体颜色
    Error: No module named books
  • 原文地址:https://www.cnblogs.com/lein317/p/5067555.html
Copyright © 2020-2023  润新知