iOS NSString 写入本地文件

#import 

NS_ASSUME_NONNULL_BEGIN

@interface LibraryCacheLogTool : NSObject

/// 写入本地library/Caches 文件夹中
/// @param str 写入的内容
+ (void)saveString:(NSString *)str;

@end

NS_ASSUME_NONNULL_END

#import "LibraryCacheLogTool.h"

@implementation LibraryCacheLogTool

+ (void)saveString:(NSString *)str {
    NSString *homeDir = NSHomeDirectory();
    NSLog(@"homeDir = %@",homeDir);
    
    //在某个范围内搜索文件夹的路径.
    //directory:获取哪个文件夹
    //domainMask:在哪个路径下搜索
    //expandTilde:是否展开路径.
    
    //这个方法获取出的结果是一个数组.因为有可以搜索到多个路径.
    NSArray *array =  NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    //在这里,我们指定搜索的是Cache目录,所以结果只有一个,取出Cache目录
    NSString *cachePath = array[0];
    NSLog(@"%@",cachePath);
    //拼接文件路径
    NSString *filePathName = [cachePath stringByAppendingPathComponent:@"Log.txt"];
    
    NSString *writeTime = [@"\n" stringByAppendingString:[@"=======================\n" stringByAppendingString:[[LibraryCacheLogTool getCurrentTime] stringByAppendingString:@"\n"]]];
    
    NSString *writeTotext = [@"\n" stringByAppendingString:@"======================="];
    
    
    writeTime = [[writeTime stringByAppendingString:str]
                 stringByAppendingString:writeTotext];
    
    NSLog(@"%@",writeTime);
    
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:filePathName]) {
        
        NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:filePathName];
        
        [fileHandle seekToEndOfFile]; //将节点跳到文件的末尾
        
        NSData *stringData = [writeTime dataUsingEncoding:NSUTF8StringEncoding];
        
        [fileHandle writeData:stringData]; // 追加写入数据
        
        [fileHandle closeFile];
    } else {
        
        [writeTime writeToFile:filePathName atomically:YES encoding:NSUTF8StringEncoding error:nil];
    }
}

+ (NSString *)getCurrentTime {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];//yyyy-MM-dd-hh-mm-ss
    [formatter setDateFormat:@"yyyy:MM:dd hh:mm:ss"];
    NSString *dateTime = [formatter stringFromDate:[NSDate date]];
    return dateTime;
}


@end

使用:


    //获取沙盒根根路径,每一个应用在手机当中都有一个文件夹,这个方法就是获取当前应用在手机里安装的文件.
    //    NSDictionary *dic = @{@"aa" : @"1221321"};
    NSArray *dic = @[@"asdsa",@"asdsdsdadad",@12332132,@"asdsds"];
    [LibraryCacheLogTool saveString:dic.description];

本地沙盒路径:
Library/Caches/Log.txt

文件写入内容如下:

=======================
2019:06:25 11:03:02
(
    asdsa,
    asdsdsdadad,
    12332132,
    asdsds
)
=======================
=======================
2019:06:25 11:07:35
(
    asdsa,
    asdsdsdadad,
    12332132,
    asdsds
)
=======================

你可能感兴趣的:(iOS NSString 写入本地文件)