iOS进阶之自定义文件管理工具
2017-02-20 本文已影响386人
child_cool
Swift 3.0版本
import UIKit
class YJFileTool: NSObject {
/// 获取项目名称
class func getProjectName() -> String {
guard let infoDictionary = Bundle.main.infoDictionary else {
return "unknown"
}
guard let projectName = infoDictionary[String(kCFBundleExecutableKey)] as? String else {
return "unknown"
}
return projectName
}
/// 返回缓存根目录 "caches"
class func getCachesDirectory() -> String {
guard let cachesPath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first else {
return "error"
}
return cachesPath + "/" + getProjectName();
}
///返回根目录路径 "document"
class func getDocumentPath() -> String {
guard let documentPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first else {
return "error"
}
return documentPath + "/" + getProjectName();
}
/// 判断文件是否存在
class func isExist(atPath filePath : String) -> Bool {
return FileManager.default.fileExists(atPath: filePath)
}
/// 创建文件目录
class func creatDir(atPath dirPath : String) -> Bool {
if isExist(atPath: dirPath) {
return false
}
do {
try FileManager.default.createDirectory(atPath: dirPath, withIntermediateDirectories: true, attributes: nil)
return true
} catch {
print(error)
return false
}
}
/// 删除文件 或者目录
class func delete(atPath filePath : String) -> Bool {
guard isExist(atPath: filePath) else {
return false
}
do {
try FileManager.default.removeItem(atPath: filePath)
return true
} catch {
print(error)
return false
}
}
///移动文件夹
class func moveDir(atPath srcPath : String, toPath desPath : String) -> Bool {
do {
try FileManager.default.moveItem(atPath: srcPath, toPath: desPath)
return true
} catch {
print(error)
return false
}
}
///创建文件
class func creatFile(atPath filePath : String, data : Data) -> Bool {
return FileManager.default.createFile(atPath: filePath, contents: data, attributes: nil)
}
///通过文件路径读取文件
class func readDataFile(atPath filePath : String) -> Data? {
guard let data = try? Data(contentsOf: URL(fileURLWithPath: filePath), options: Data.ReadingOptions.mappedIfSafe) else {
return nil
}
return data
}
///通过文件名读取文件
class func readDataFile(atName fileName : String) -> Data? {
return readDataFile(atPath: getFilePath(fileName))
}
/// 获取文件路径
class func getFilePath(_ fileName : String) -> String {
return getDocumentPath() + "/" + fileName
}
/// 文件写入
class func writeDataToFile(_ fileName : String,data : Data) -> Bool {
return creatFile(atPath: getFilePath(fileName), data: data)
}
/// 获取单个文件的大小
class func getFileSize(atPath filePath : String) -> CGFloat {
guard isExist(atPath: filePath) else {
return 0
}
guard let dict = try? FileManager.default.attributesOfItem(atPath: filePath) as NSDictionary else {
return 0
}
return CGFloat(dict.fileSize())
}
/// 遍历文件夹获取目录下的所有的文件 遍历计算大小
class func folderSizeAtPath(folderPath:String) -> CGFloat
{
if folderPath.characters.count == 0 {
return 0
}
guard isExist(atPath: folderPath) else {
return 0
}
var fileSize:CGFloat = 0.0
do {
let files = try FileManager.default.contentsOfDirectory(atPath: folderPath)
for file in files {
let path = getDocumentPath() + "/\(file)"
fileSize = fileSize + getFileSize(atPath: path)
}
} catch {
}
return fileSize/(1000.0*1000.0)
}
}
OC版本
.h文件
#import <Foundation/Foundation.h>
@interface YJFileTool : NSObject
/** 返回缓存根目录 "caches" */
+(NSString *)getCachesDirectory;
/** 返回根目录路径 "document" */
+ (NSString *)getDocumentPath;
/** 创建文件夹 */
+(BOOL)creatDir:(NSString*)dirPath;
/** 删除文件夹 */
+(BOOL)deleteDir:(NSString*)dirPath;
/** 移动文件夹 */
+(BOOL)moveDir:(NSString*)srcPath to:(NSString*)desPath;
/** 创建文件 */
+ (BOOL)creatFile:(NSString*)filePath withData:(NSData*)data;
/** 读取文件 */
+(NSData*)readFile:(NSString *)filePath;
/** 删除文件 */
+(BOOL)deleteFile:(NSString *)filePath;
/** 返回 文件全路径 */
+ (NSString*)getFilePath:(NSString*) fileName;
/** 在对应文件保存数据 */
+ (BOOL)writeDataToFile:(NSString*)fileName data:(NSData*)data;
/** 从对应的文件读取数据 */
+ (NSData*)readDataFromFile:(NSString*)fileName;
/** 判断文件是否存在 */
+ (BOOL)isExistAtPath:(NSString *)filePath;
/** 计算文件大小 */
+ (unsigned long long)fileSizeAtPath:(NSString *)filePath;
/** 计算整个文件夹中所有文件大小 */
+ (unsigned long long)folderSizeAtPath:(NSString*)folderPath;
@end
.m文件
#import "YJFileTool.h"
@implementation YJFileTool
//返回缓存根目录 "caches"
+(NSString *)getCachesDirectory
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *caches = [paths firstObject];
//获取所有信息字典
NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
NSString *executableFile = [infoDictionary objectForKey:(NSString *)kCFBundleExecutableKey]; //获取项目名称
NSString *filePath = [NSString stringWithFormat:@"%@/%@",caches,executableFile];
return filePath;
}
//返回根目录路径 "document"
+ (NSString *)getDocumentPath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPath = [paths firstObject];
//获取所有信息字典
NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
NSString *executableFile = [infoDictionary objectForKey:(NSString *)kCFBundleExecutableKey]; //获取项目名称
NSString *filePath = [NSString stringWithFormat:@"%@/%@",documentPath,executableFile];
return filePath;
}
//创建文件目录
+(BOOL)creatDir:(NSString*)dirPath
{
if ([[NSFileManager defaultManager] fileExistsAtPath:dirPath])//判断dirPath路径文件夹是否已存在,此处dirPath为需要新建的文件夹的绝对路径
{
return NO;
}
else
{
[[NSFileManager defaultManager] createDirectoryAtPath:dirPath withIntermediateDirectories:YES attributes:nil error:nil];//创建文件夹
return YES;
}
}
//删除文件目录
+(BOOL)deleteDir:(NSString*)dirPath
{
if([[NSFileManager defaultManager] fileExistsAtPath:dirPath])//如果存在临时文件的配置文件
{
NSError *error=nil;
return [[NSFileManager defaultManager] removeItemAtPath:dirPath error:&error];
}
return NO;
}
//移动文件夹
+(BOOL)moveDir:(NSString*)srcPath to:(NSString*)desPath;
{
NSError *error=nil;
if([[NSFileManager defaultManager] moveItemAtPath:srcPath toPath:desPath error:&error]!=YES)// prePath 为原路径、 cenPath 为目标路径
{
NSLog(@"移动文件失败");
return NO;
}
else
{
NSLog(@"移动文件成功");
return YES;
}
}
//创建文件
+ (BOOL)creatFile:(NSString*)filePath withData:(NSData*)data
{
return [[NSFileManager defaultManager] createFileAtPath:filePath contents:data attributes:nil];
}
//读取文件
+(NSData*)readFile:(NSString *)filePath
{
return [NSData dataWithContentsOfFile:filePath options:0 error:NULL];
}
//删除文件
+(BOOL)deleteFile:(NSString *)filePath
{
return [self deleteDir:filePath];
}
+ (NSString *)getFilePath:(NSString *)fileName
{
NSString *dirPath = [[self getDocumentPath] stringByAppendingPathComponent:fileName];
return dirPath;
}
+ (BOOL)writeDataToFile:(NSString*)fileName data:(NSData*)data
{
NSString *filePath=[self getFilePath:fileName];
return [self creatFile:filePath withData:data];
}
+ (NSData*)readDataFromFile:(NSString*)fileName
{
NSString *filePath=[self getFilePath:fileName];
return [self readFile:filePath];
}
// 判断文件是否存在
+ (BOOL)isExistAtPath:(NSString *)filePath {
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL isExist = [fileManager fileExistsAtPath:filePath];
return isExist;
}
// 计算文件大小
+ (unsigned long long)fileSizeAtPath:(NSString *)filePath {
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([self isExistAtPath:filePath]) {
unsigned long long fileSize = [[fileManager attributesOfItemAtPath:filePath error:nil] fileSize];
return fileSize;
} else {
NSLog(@"file is not exist");
return 0;
}
}
// 计算整个文件夹中所有文件大小
+ (unsigned long long)folderSizeAtPath:(NSString*)folderPath {
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([self isExistAtPath:folderPath]) {
NSEnumerator *childFileEnumerator = [[fileManager subpathsAtPath:folderPath] objectEnumerator];
unsigned long long folderSize = 0;
NSString *fileName = @"";
while ((fileName = [childFileEnumerator nextObject]) != nil){
NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
folderSize += [self fileSizeAtPath:fileAbsolutePath];
}
return folderSize / (1024.0 * 1024.0);
} else {
NSLog(@"file is not exist");
return 0;
}
}
@end