zoukankan      html  css  js  c++  java
  • 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"]);




  • 相关阅读:
    java多线程编程(一)
    java的本地文件操作
    Java基础总结(二)
    Gym 100851 Distance on Triangulation
    Gym 100851 题解
    Gym 101482 题解
    CodeForces Round 521 div3
    zoj 5823 Soldier Game 2018 青岛 I
    CodeForces round 520 div2
    CodeForces 1042 F Leaf Sets 贪心
  • 原文地址:https://www.cnblogs.com/lein317/p/5067555.html
Copyright © 2011-2022 走看看