工作需要写了一个操作文件的类,Swift版本的之前已经有过了,我是地址 里面的 MUFile 就是了。
重写了一下,感觉文件操作这块。无非就是几个点。
获取地址。
创建文件。
删除文件。
NJTools.h
//
// NJTools.h
//
// Created by 黄穆斌 on 16/3/6.
//
#import <Foundation/Foundation.h>
typedef NS_ENUM(u_int8_t, FolderType) {
DocumentFolder,
LibraryFolder,
TemporaryFolder,
CachesFolder
};
@interface NJTools : NSObject
/**
Get the path with app.
*/
+ (NSString *)getPath:(FolderType)type;
/**
Create the directory.
*/
+ (void)createPath:(NSString *)path;
/**
Remove the file.
*/
+ (void)removeFile:(NSString *)path;
/** video Path */
+ (NSString *)videoPath;
/** Image Path */
+ (NSString *)imagePath;
@end
NJTools.m
//
// NJTools.m
// MoeNightjar
//
// Created by 黄穆斌 on 16/3/6.
// Copyright © 2016年 張帥. All rights reserved.
//
#import "NJTools.h"
@implementation NJTools
/**
Get the path with app.
File: "D" = "Document"; "L" = "Library"; "T" = "Temporary"; "C" = "Caches";
Other or nil all is the NSHomeDirectory.
*/
+ (NSString *)getPath:(FolderType)type {
switch (type) {
case DocumentFolder:
return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, true) firstObject];
case LibraryFolder:
return [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, true) firstObject];
case TemporaryFolder:
return NSTemporaryDirectory();
case CachesFolder:
return [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, true) firstObject];
}
}
/**
Create the directory.
*/
+ (void)createPath:(NSString *)path {
if (path && ![path isEqualToString:@""]) {
NSFileManager *manager = [NSFileManager defaultManager];
if ([manager fileExistsAtPath:path]) {
return;
}
[manager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
}
}
/**
Remove the file.
*/
+ (void)removeFile:(NSString *)path {
NSFileManager *manager = [NSFileManager defaultManager];
[manager removeItemAtPath:path error:nil];
}
/** video Path */
+ (NSString *)videoPath {
return [NSString stringWithFormat:@"%@%@", [self getPath:TemporaryFolder], @"video"];
}
/** Image Path */
+ (NSString *)imagePath {
return [NSString stringWithFormat:@"%@%@", [self getPath:TemporaryFolder], @"image"];
}
/** 获取路径下的所有文件文件名 */
+ (NSArray *)allFileNamesToPath:(NSString *)path {
return [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:path error:nil];
}
@end