iOS 利用FZEasyFile本地保存 和 常规保存

1、常规保存(较麻烦)

NSFileManager *fileManager = [NSFileManager defaultManager];

    //获取document路径,括号中属性为当前应用程序独享
    NSArray *directoryPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDirectory = [directoryPaths objectAtIndex:0];

    //查找文件夹,如果不存在,就创建一个文件夹
    NSString *dir = [documentDirectory stringByAppendingPathComponent:@SAVEDIR];
    NSLog(@"cache dir %@", dir);
    if(![fileManager fileExistsAtPath:dir])
    {
        if(![fileManager createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil])
        {
            NSLog(@"create dir:(%@) error", dir);
            return;
        }
    }

    //定义记录文件全名以及路径的字符串filePath
    NSString *filePath = [dir stringByAppendingPathComponent:[[NSString alloc]initWithFormat:@"/%@", filename]];

    //查找文件,如果不存在,就创建一个文件
    NSData *data = [lHtml dataUsingEncoding:NSUTF8StringEncoding];
    if (![fileManager fileExistsAtPath:filePath]) {
        [fileManager createFileAtPath:filePath contents:data attributes:nil];
    }

2、FZEasyFile保存导入的文件:

//

//  FZEasyFile.h

//  FZEasyFile

//

//  Created by zhou jun on 14-4-29.

//  Copyright (c) 2014年 shannonchou. All rights reserved.

//

#import <Foundation/Foundation.h>

@interface FZEasyFile : NSObject

/**

singleton pattern.

@return the shared instance.

*/

+ (FZEasyFile *)sharedInstance;

/**

convert the short file name to full file name. e.g. "mycache/user/icon.png" -> "/Users/zhoujun/Library/Application Support/iPhone Simulator/7.1/Applications/ABCE2119-E864-4492-A3A9-A238ADA74BE5/Documents/mycache/user/icon.png".

@return full file name.

*/

- (NSString *)fullFileName:(NSString *)shortFileName;

/**

test if the file exists.

@param fileName file path and file name, e.g. "mycache/user/icon.png".

@return YES if exists, NO otherwise.

*/

- (BOOL)isFileExists:(NSString *)fileName;

/**

create a file

@param fileName fileName file path and file name, e.g. "mycache/user/icon.png".

@param shouldOverwrite YES:if the file exists then overwirte it, NO:if the file exists then do nothing

*/

- (void)createFile:(NSString *)fileName overwrite:(BOOL)shouldOverwrite;

@end

//

//  FZEasyFile.m

//  FZEasyFile

//

//  Created by zhou jun on 14-4-29.

//  Copyright (c) 2014年 shannonchou. All rights reserved.

//

#import "FZEasyFile.h"

@implementation FZEasyFile

static FZEasyFile *instance;

+ (FZEasyFile *)sharedInstance {

if (!instance) {

@synchronized (FZEasyFile.class){

if (!instance) {

instance = [[FZEasyFile alloc] init];

}

}

}

return instance;

}

- (NSString *)fullFileName:(NSString *)shortFileName {

//search the "document" path

NSArray *directoryPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentDirectory = [directoryPaths objectAtIndex:0];

NSString *file = [documentDirectory stringByAppendingPathComponent:shortFileName];

return file;

}

- (BOOL)isFileExists:(NSString *)fileName {

NSFileManager *fileManager = [NSFileManager defaultManager];

NSString *file = [self fullFileName:fileName];

return [fileManager fileExistsAtPath:file];

}

- (void)createFile:(NSString *)fileName overwrite:(BOOL)shouldOverwrite {

NSFileManager *fileManager = [NSFileManager defaultManager];

//create file directory, include multilayer directory

NSRange lastTag = [fileName rangeOfString:@"/" options:NSBackwardsSearch];

if (lastTag.location != NSNotFound && lastTag.location != 0) {

NSString *shortDir = [fileName substringToIndex:lastTag.location];

NSString *fullDir = [self fullFileName:shortDir];

NSLog(@"full directory: %@", fullDir);

if (![fileManager fileExistsAtPath:fullDir]) {

[fileManager createDirectoryAtPath:fullDir withIntermediateDirectories:YES attributes:nil error:nil];

}

}

NSString *file = [self fullFileName:fileName];

NSLog(@"full file name:%@", file);

//file not exists or want to overwrite it

if (shouldOverwrite || ![fileManager fileExistsAtPath:file]) {

BOOL suc = [fileManager createFileAtPath:file contents:nil attributes:nil];

NSLog(@"create file(%@) %@", file, suc ? @"successfully" : @"failed");

}

}

@end

使用方法:

导入头文件:



#import "FZEasyFile.h"

判断地址是否已存在



[EasyFile isFileExists:@"my/file/path/info.txt"]

创建



[EasyFile createFile:"my/file/path/info.txt" overwrite:NO];

写入文件中:拼接和覆盖写入



[FZEasyFile writeFile:"my/file/path/info.txt" contents:[@"a" dataUsingEncoding:NSUTF8StringEncoding] append:NO];
[FZEasyFile writeFile:"my/file/path/info.txt" contents:[@"b" dataUsingEncoding:NSUTF8StringEncoding] append:YES];

After these calling the content of the file is "ab".


删除文件



[FZEasyFile removeFile:"my/file/path/info.txt"];
[FZEasyFile removeFile:"my/file/path"];

获取绝对路径(实际存储路径)



NSString *fullName = [EasyFile fullFileName:"my/file/path/info.txt"];

转换

After getting the full name, you can pass it to other API, such as NSInputStream:



NSInputStream *input = [NSInputStream inputStreamWithFileAtPath:fullName];

 
时间: 2024-08-29 08:28:37

iOS 利用FZEasyFile本地保存 和 常规保存的相关文章

ASP.NET下载远程图片保存到本地的方法、保存抓取远程图片

ASP.NET下载远程图片保存到本地的方法.保存抓取远程图片 2012-05-16 11:25:51     我来说两句      收藏    我要投稿 以下介绍两种方法:1.利用WebRequest,WebResponse 类WebRequest wreq=WebRequest.Create("http://up.2cto.com/2012/0516/20120516112717995.gif");    HttpWebResponse wresp=(HttpWebResponse)

利用wget下载文件,并保存到指定目录

利用WGET下载文件,并保存到指定目录 [email protected] ~/下载 $ wget -P /home/cbx/下载/PDF https://www.linuxmint.com/documentation/user-guide/Cinnamon/chinese_16.0.pdf https://www.linuxmint.com/documentation.php wget是Linux上一个非常不错的下载指令,而其指令的内容虽然说是非常简单,但内藏许多的参数,也算是Linux工作者

Ruby1.9.3-下载网络图片至本地,并按编号保存。

#本程序功能:下载网络图片至本地,并按编号保存. #使用Ruby1.9.3在winxp_sp3下编写. require 'nokogiri' require 'open-uri' #以下 根据网址解析网页. page = Nokogiri::HTML(open("http://www.169bb.com/News/2014-12-20/093288.htm")) arrlen = page.css('img').length mypics = Array.new(arrlen) #以下

安卓实训第十天:利用SharedPreferences来实现数据的保存和读取,以及实现手机电话备份,XMLserializer

一.利用SharedPreferences来实现数据的保存和读取: 1.Mainactivity: package com.example.sharedpreferencesdemo; import com.example.sharedpreferencesdemo.util.SharedPreferencesUtil; import android.app.Activity; import android.app.AlertDialog; import android.content.Cont

【IOS】 遍历info 的所有内容 &amp;&amp; 保存设备唯一UUID

/**获取设备的imie*/ std::string DeviceInfo::getIMIE() { #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) NSString*bunider = nil; NSBundle* mainBundle = [NSBundle mainBundle]; NSDictionary* infoDictionary = [mainBundle infoDictionary]; id key; NSArray* keys = [

iOS五种本地缓存数据方式

iOS五种本地缓存数据方式 iOS本地缓存数据方式有五种:前言 1.直接写文件方式:可以存储的对象有NSString.NSArray.NSDictionary.NSData.NSNumber,数据全部存放在一个属性列表文件(*.plist文件)中. 2.NSUserDefaults(偏好设置),用来存储应用设置信息,文件放在perference目录下. 3.归档操作(NSkeyedArchiver),不同于前面两种,它可以把自定义对象存放在文件中. 4.coreData:coreData是苹果官

IOS NSUserDefaults-轻量级本地数据存储

IOS NSUserDefaults-轻量级本地数据存储 IOS 针对用户数据持久化处理提供了多种处理方式:NSUserDefaults.plist 以及 sqlite3 数据库 都是很不错的选择! NSUserDefaults 是一种轻量级本地数据存储,操作方便,但仅支持Bool.Float.NSInteger.Object.Double.Url 这六种数据类型的存储 NSUserDefaults 提供了添加.读取以及移除等方法,供开发者调用,具体示例如下: GNSUserDefaults.h

iOS利用AFNetworking(AFN) 实现图片上传

1.上传图片以二进制流的形式上传 1 #pragma mark - 文件上传  2 - (IBAction)uploadImage  3 {  4     /*  5      此段代码如果需要修改,可以调整的位置  6        7      1. 把upload.php改成网站开发人员告知的地址  8      2. 把file改成网站开发人员告知的字段名  9      */ 10     // 1. httpClient->url 11      12     // 2. 上传请求P

利用yum本地源安装,解决电脑无法上网也能安软件的问题

最近上Linux网络架构课,学到了一个不错的方法,即使不能连接互联网,也可以安装软件,那就是利用yum,进行本地源的安装,简单又方便,下面就介绍给大家: 一.创建本地源的前提是有你一个包含你需要文件的镜像包,然后在你安装的虚拟机上,点击设置,勾选连接,并导入镜像包,如下图: 二.导入成功后,你的虚拟机桌面上会出现一个你需要的镜像包. 三.打开电脑上的终端,进行如下配置: 先检查自己是否已安装过所需的软件 如果没有则开始创建本地源 首先,在root用户下创建一个yum文件夹,然后利用df-h命令,