获取document目录路径
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
NSLog(@"path:%@", path);
获取cache目录
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
NSLog(@"%@", path);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
NSLog(@"%@", path);
获取tmp目录
NSString *tmpDir = NSTemporaryDirectory();
NSLog(@"%@", tmpDir);
文件写入的一种方式
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
if (!docDir) {
NSLog(@"Documents 目录未找到");
}
NSArray *array = [[NSArray alloc] initWithObjects:@"内容",@"content",nil];
NSString *filePath = [docDir stringByAppendingPathComponent:@"testFile.txt"];
[array writeToFile:filePath atomically:YES];
利用FileManager创建目录并在该目录中创建文件
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSLog(@"documentsDirectory%@",documentsDirectory);
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *testDirectory = [documentsDirectory stringByAppendingPathComponent:@"test"];
// 创建目录
[fileManager createDirectoryAtPath:testDirectory withIntermediateDirectories:YES attributes:nil error:nil];
NSString *testPath = [testDirectory stringByAppendingPathComponent:@"test00.txt"];
NSString *testPath2 = [testDirectory stringByAppendingPathComponent:@"test22.txt"];
NSString *testPath3 = [testDirectory stringByAppendingPathComponent:@"test33.txt"];
NSString *string = @"写入内容,write String";
[fileManager createFileAtPath:testPath contents:[string dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];
[fileManager createFileAtPath:testPath2 contents:[string dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];
[fileManager createFileAtPath:testPath3 contents:[string dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];
获取指定路径下所有文件路径的一个方法,也是利用fileManager
+(NSArray *)getAllFileAtPath:(NSString *)dirPath
{
NSMutableArray* array = [NSMutableArray arrayWithCapacity:50];
NSFileManager* fileManager = [NSFileManager defaultManager];
NSArray* tempArray = [fileManager contentsOfDirectoryAtPath:dirPath error:nil];
for (NSString* fileName in tempArray) {
if(![fileName isEqualToString:@"Snapshots"] && ![fileName isEqualToString:@".DS_Store"])
{
BOOL flag = YES;
NSString* fullPath = [dirPath stringByAppendingPathComponent:fileName];
if ([fileManager fileExistsAtPath:fullPath isDirectory:&flag]) {
if (!flag) {
[array addObject:fullPath];
}
}
}
}
return array;
}