1,引用和使用文件

NSFileManager 是一个单例对象,在mac应用中可以获取任何地址,在IOS中获取的是相对应的应用程序的地址。可以使用 defaultManager 来得到当前应用程序地址,例如。

NSFileManager *fileManager = [NSFileManager defaultManager];

模拟器目录 /Users/username/Library/Application Support/iPhone Simulator/

一旦有了参考,你便可以得到相应目录,例如你想得到currentDirectoryPath

目录。

NSString *currentDirectoryPath = [fileManager currentDirectoryPath];

想切换目录,用changeCurrentDirectoryPath,如

[fileManager changeCurrentDirectoryPath:@"/Users/Shared”];

代码例子。

NSFileManager *fileManager = [NSFileManager defaultManager];

NSString *currentDirectoryPath = [fileManager currentDirectoryPath];

NSLog(@"currentDirectoryPath = %@---", currentDirectoryPath);

[fileManager changeCurrentDirectoryPath:@"/Users/Shared"];

currentDirectoryPath = [fileManager currentDirectoryPath];

NSLog(@"currentDirectoryPath = %@+++", currentDirectoryPath);

2,mac目录引用

使用NSSearchPathForDirectoriesInDomains

例如

NSString *bundlePath = [[NSBundle mainBundle] bundlePath];

NSLog(@"%@++", bundlePath);

打印的值大概是

/Users/guanliyang/Library/Developer/Xcode/DerivedData/filePath-dgfhcnomuvxhzpepzbrxbrfkhkkz/Build/Products/Debug++

如果想得到文档目录

NSString *directoryPathName = [NSSearchPathForDirectoriesInDomains

(NSDocumentDirectory,NSAllDomainsMask, YES) lastObject];

更多参数请参考原著objective-C recipes。

3,获取IOS引用目录

NSString *bundlePath = [[NSBundle mainBundle] bundlePath];

NSLog(@"%@", bundlePath);

这个得到的是你IOS应用的主目录,/Users/guanliyang/Library/Application Support/iPhone Simulator/7.1/Applications/1A888392-101B-40B1-A47A-195C19DBC18E/aa.app

如果你想得到模拟器的文档目录,你可以这样做

NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) lastObject];

NSLog(@"%@", documentsDirectory);

还有其他几个选项,IOS模拟器默认生成的几个目录

NSDocumentDirectory  Location for user-generated content (read-write, backed up) The

NSLibraryDirectory  app’s library directory (read-write, backed up)

NSCachesDirectory  A directory for cached files (read-write, not backed up)

默认只生成这三个目录。

4,获取文件属性。

先指定文件

NSFileManager *fileManager = [NSFileManager defaultManager];

NSString *filePathName = @"/Users/Shared/textfile.txt”;

声明error

NSError *error = nil;

给定文件路径,试着读取文件并查看是否有错。

NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:filePathName error:&error];

如果没有错误,获取文件相关信息。

if(!error){

NSDate *dateFileCreated = [fileAttributes valueForKey:NSFileCreationDate];

NSString *fileType = [fileAttributes valueForKey:NSFileType];

}

还有很多相关信息可打印,比如大小,所属用户,文件个数等等....

5,获取文件子目录和目录中的目录。

先得到文件列表

NSFileManager *fileManager = [NSFileManager defaultManager];

NSString *sharedDirectory = @"/Users/Shared”;

NSError *error = nil;

NSArray *listOfFiles = [fileManager contentsOfDirectoryAtPath:sharedDirectory

error:&error];

递归目录,可以使用subpathsOfDirectoryAtPath:error

例如

NSArray *listOfSubPaths = [fileManager subpathsOfDirectoryAtPath:sharedDirectory

error:&error];

例子代码

int main(int argc, const char * argv[])

{

@autoreleasepool {

NSFileManager *fileManager = [NSFileManager defaultManager];

NSString *sharedDirectory = @"/Users/Shared";

NSError *error = nil;

NSArray *listOfFiles = [fileManager contentsOfDirectoryAtPath:sharedDirectory

error:&error];

if(!error)

NSLog(@"Contents of shared directory: %@", listOfFiles);

NSArray *listOfSubPaths = [fileManager subpathsOfDirectoryAtPath:sharedDirectory

error:&error];

if(!error)

NSLog(@"Sub Paths of shared directory”: %@", listOfSubPaths);

}

return 0;

}

6,管理目录

用代码操作目录。

使用NSFileManager,

createDirectoryAtPath:withIntermediateDirectories:attributes:error:可以创建目录,

moveItemAtPath:toPath:error: 可以移动目录,

removeItemAtPath:error:删除目录,

copyItemAtPath:toPath:error:拷贝目录

具体代码

NSFileManager *fileManager = [NSFileManager defaultManager];

NSString *sharedDirectory = @"/Users/Shared/NewDirectory1/NewSubDirectory1";

NSError *error = nil;

创建

BOOL directoryCreated = [fileManager createDirectoryAtPath:newDirectory

withIntermediateDirectories:YES

attributes:nil

error:&error];

该函数返回布尔值,提示是否创建成功。

同理,移动文件。

NSString *directoryMovedTo = @"/Users/Shared/NewSubDirectory1";

BOOL directoryMoved = [fileManager moveItemAtPath:newDirectory

toPath:directoryMovedTo

error:&error];

删除目录

NSString *directoryToRemove = @"/Users/Shared/NewDirectory1";

BOOL directoryRemoved =[fileManager removeItemAtPath:directoryToRemove

error:&error];

复制目录。

NSString *directoryToCopy = @"/Users/Shared/NewSubDirectory1";

NSString *directoryToCopyTo = @"/Users/Shared/CopiedDirectory";

BOOL directoryCopied =[fileManager copyItemAtPath:directoryToCopy

toPath:directoryToCopyTo

error:&error];

具体代码例子。

NSFileManager *fileManager = [NSFileManager defaultManager];

NSString *newDirectory =@"/Users/Shared/NewDirectory1/NewSubDirectory1";

NSError *error = nil;

BOOL directoryCreated = [fileManager createDirectoryAtPath:newDirectory

withIntermediateDirectories:YES

attributes:nil

error:&error];

if(!error)

NSLog(@"directoryCreated = %i with no error", directoryCreated);

else

NSLog(@"directoryCreated = %i with error %@", directoryCreated, error);

NSString *directoryMovedTo = @"/Users/Shared/NewSubDirectory1";

BOOL directoryMoved = [fileManager moveItemAtPath:newDirectory

toPath:directoryMovedTo

error:&error];

if(!error)

NSLog(@"directoryMoved = %i with no error", directoryMoved);

else

NSLog(@"directoryMoved = %i with error %@", directoryMoved, error);

NSString *directoryToRemove = @"/Users/Shared/NewDirectory1";

BOOL directoryRemoved =[fileManager removeItemAtPath:directoryToRemove

error:&error];

if(!error)

NSLog(@"directoryRemoved = %i with no error", directoryRemoved);

else

NSLog(@"directoryRemoved = %i with error %@", directoryRemoved, error);

NSString *directoryToCopy = @"/Users/Shared/NewSubDirectory1";

NSString *directoryToCopyTo = @"/Users/Shared/CopiedDirectory";

BOOL directoryCopied =[fileManager copyItemAtPath:directoryToCopy

toPath:directoryToCopyTo

error:&error];

if(!error)

NSLog(@"directoryCopied = %i with no error", directoryCopied);

else

NSLog(@"directoryCopied = %i with error %@", directoryCopied, error);

7,管理文件。

添加,移动,复制,删除文件。

代码例子,图片不能访问可新找一图片地址。

NSFileManager *fileManager = [NSFileManager defaultManager];

NSURL *url = [NSURL URLWithString:@"http://img5.imgtn.bdimg.com/it/u=3163907393,1865504758&fm=23&gp=0.jpg”];

用NSData为图片对象,

NSData *dataObject = [NSData dataWithContentsOfURL:url];

创建图片

NSString *newFile = @"/Users/Shared/apples-oranges.jpg";

BOOL fileCreated = [fileManager createFileAtPath:newFile

contents:dataObject

attributes:nil];

移动图片

NSError *error = nil;

NSString *fileMovedTo = @"/Users/Shared/apples-oranges-moved.jpg";

BOOL fileMoved = [fileManager moveItemAtPath:newFile

toPath:fileMovedTo

error:&error];

删除图片

NSString *fileToRemove = @"/Users/Shared/apples-oranges-moved.jpg";

BOOL fileRemoved =[fileManager removeItemAtPath:fileToRemove

error:&error];

复制图片

NSString *fileToCopy = @"/Users/Shared/apples-oranges-moved.jpg";

NSString *copiedFileName = @"/Users/Shared/apples-oranges-backup-copy.jpg";

BOOL fileCopied = [fileManager copyItemAtPath:fileToCopy

toPath:copiedFileName

error:&error];

具体代码例子。

NSFileManager *fileManager = [NSFileManager defaultManager];

NSURL *url = [NSURL URLWithString:@"http://www.baidu.com/img/baidu_sylogo1.gif"];

NSData *dataObject = [NSData dataWithContentsOfURL:url];

NSString *newFile = @"/Users/Shared/apples-oranges.jpg";

BOOL fileCreated = [fileManager createFileAtPath:newFile

contents:dataObject

attributes:nil];

NSLog(@"fileCreated = %i with no error", fileCreated);

NSError *error = nil;

NSString *fileMovedTo = @"/Users/Shared/apples-oranges-moved.jpg";

BOOL fileMoved = [fileManager moveItemAtPath:newFile

toPath:fileMovedTo

error:&error];

if(!error)

NSLog(@"fileMoved = %i with no error", fileMoved);

else

NSLog(@"fileMoved = %i with error %@", fileMoved, error);

NSString *fileToCopy = @"/Users/Shared/apples-oranges-moved.jpg";

NSString *copiedFileName = @"/Users/Shared/apples-oranges-backup-copy.jpg";

BOOL fileCopied = [fileManager copyItemAtPath:fileToCopy

toPath:copiedFileName

error:&error];

if(!error)

NSLog(@"fileCopied = %i with no error", fileCopied);

else

NSLog(@"fileCopied = %i with error %@", fileCopied, error);

NSString *fileToRemove = @"/Users/Shared/apples-oranges-moved.jpg";

BOOL fileRemoved =[fileManager removeItemAtPath:fileToRemove

error:&error];

if(!error)

NSLog(@"fileRemoved = %i with no error", fileRemoved);

else

NSLog(@"fileRemoved = %i with error %@", fileRemoved, error);

可以更改容易查看目录做具体测试。

8,检查文件状态。

常用方法。

 fileExistsAtPath:

 isReadableFileAtPath:

 isWritableFileAtPath:

 isExecutableFileAtPath:  isDeletableFileAtPath:.

检查文件是否存在。

NSFileManager *fileManager = [NSFileManager defaultManager];

NSString *filePathName = @"/Users/Shared/textfile.txt”;

BOOL fileExists = [fileManager fileExistsAtPath:filePathName];

文件是否可读

BOOL fileIsReadable = [fileManager isReadableFileAtPath:filePathName];

是否可写

BOOL fileIsWriteable = [fileManager isWritableFileAtPath:filePathName];

最后,文件是否可删除。

BOOL fileIsDeleteable = [fileManager isDeletableFileAtPath:filePathName];

具体代码例子。

NSFileManager *fileManager = [NSFileManager defaultManager];

NSString *filePathName = @"/Users/Shared/textfile.txt";

BOOL fileExists = [fileManager fileExistsAtPath:filePathName];

if(fileExists)

NSLog(@"%@ exists", filePathName);

else

NSLog(@"%@ doesn't exist", filePathName);

BOOL fileIsReadable = [fileManager isReadableFileAtPath:filePathName];

if(fileIsReadable)

NSLog(@"%@ is readable", filePathName);

else

NSLog(@"%@ isn't readable", filePathName);

BOOL fileIsWriteable = [fileManager isWritableFileAtPath:filePathName];

if(fileIsWriteable)

NSLog(@"%@ is writable", filePathName);

else

NSLog(@"%@ isn't writable", filePathName);

BOOL fileIsExecutable = [fileManager isExecutableFileAtPath:filePathName];

if(fileIsExecutable)

NSLog(@"%@ is an executable", filePathName);

else

NSLog(@"%@ isn't an executable", filePathName);

BOOL fileIsDeleteable = [fileManager isDeletableFileAtPath:filePathName];

if(fileIsDeleteable)

NSLog(@"%@ is deletable", filePathName);

else

NSLog(@"%@ isn't an deletable", filePathName);

没文件可以自己touch创建一个。

9,更改文件属性。

文件管理对象,文件,错误对象。

NSFileManager *fileManager = [NSFileManager defaultManager];

NSString *filePathName = @"/Users/Shared/textfile.txt";

NSError *error = nil;

建立一个字典数组以便获取文件属性列表。

NSMutableDictionary *attributes = [[NSMutableDictionary alloc] init];

[attributes setObject:[NSDate date] forKey:NSFileModificationDate];

我们只改一下文件的修改日期

BOOL attributeChanged = [fileManager setAttributes:attributes

ofItemAtPath:filePathName

error:&error];

具体代码

NSFileManager *fileManager = [NSFileManager defaultManager];

NSString *filePathName = @"/Users/Shared/textfile.txt";

NSError *error = nil;

//Get the file attributes so you can compare later on:

NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:filePathName

error:&error];

if(!error)

NSLog(@"%@ file attributes (before): %@",filePathName, fileAttributes);

NSMutableDictionary *attributes = [[NSMutableDictionary alloc] init];

[attributes setObject:[NSDate date] forKey:NSFileModificationDate];

BOOL attributeChanged = [fileManager setAttributes:attributes

ofItemAtPath:filePathName

error:&error];

if(error)

NSLog(@"There was an error: %@", error);

else{

NSLog(@"attributeChanged = %i", attributeChanged);

//Get the file attributes to see the change:

NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:filePathName

error:&error];

if(!error)

NSLog(@"%@ file attributes (after): %@",filePathName, fileAttributes);

ObjectiveC 文件操作一的更多相关文章

  1. ObjectiveC 文件操作二

    10,文件委托,以便操作文件.头部看起来像是这样. @interface MyFileManager : NSObject @property(strong)NSFileManager *fileMa ...

  2. 【.NET深呼吸】Zip文件操作(1):创建和读取zip文档

    .net的IO操作支持对zip文件的创建.读写和更新.使用起来也比较简单,.net的一向作风,东西都准备好了,至于如何使用,请看着办. 要对zip文件进行操作,主要用到以下三个类: 1.ZipFile ...

  3. 野路子出身PowerShell 文件操作实用功能

    本文出处:http://www.cnblogs.com/wy123/p/6129498.html 因工作需要,处理一批文件,本想写C#来处理的,后来想想这个是PowerShell的天职,索性就网上各种 ...

  4. Node基础篇(文件操作)

    文件操作 相关模块 Node内核提供了很多与文件操作相关的模块,每个模块都提供了一些最基本的操作API,在NPM中也有社区提供的功能包 fs: 基础的文件操作 API path: 提供和路径相关的操作 ...

  5. 归档NSKeyedArchiver解归档NSKeyedUnarchiver与文件管理类NSFileManager (文件操作)

    ========================== 文件操作 ========================== 一.归档NSKeyedArchiver 1.第一种方式:存储一种数据. // 归档 ...

  6. SQL Server附加数据库报错:无法打开物理文件,操作系统错误5

    问题描述:      附加数据时,提示无法打开物理文件,操作系统错误5.如下图: 问题原因:可能是文件访问权限方面的问题. 解决方案:找到数据库的mdf和ldf文件,赋予权限即可.如下图: 找到mdf ...

  7. 通过cmd完成FTP上传文件操作

    一直使用 FileZilla 这个工具进行相关的 FTP 操作,而在某一次版本升级之后,发现不太好用了,连接老是掉,再后来完全连接不上去. 改用了一段时间的 Web 版的 FTP 工具,后来那个页面也 ...

  8. Linux文件操作的主要接口API及相关细节

    操作系统API: 1.API是一些函数,这些函数是由linux系统提供支持的,由应用层程序来使用,应用层程序通过调用API来调用操作系统中的各种功能,来干活 文件操作的一般步骤: 1.在linux系统 ...

  9. C语言的fopen函数(文件操作/读写)

    头文件:#include <stdio.h> fopen()是一个常用的函数,用来以指定的方式打开文件,其原型为:    FILE * fopen(const char * path, c ...

随机推荐

  1. 获取ini文件所有的Sections和Keys

    获取ini文件中所有的Sections和Keys,并以pair对的方式存入到vector中 #include <iostream> #include <windows.h> # ...

  2. OpenID倡议:别再创建新的用户名和密码

    原文作者:Jeff Atwood 随着Stack Overflow开发工作的逐步深入,我们不可回避地碰到了这个问题:我们需要让用户登录,即使网络上用户名/密码已经泛滥成灾,我们也只能随波逐流.我已经有 ...

  3. SVN版本控制服务器安装与配置

    版本管理在我们日常学习中一般接触不到,因为我们都是一个人在学习与开发一些练习的项目.但是实际中,一般项目都是协同开发的,这样就需要一个版本管理工具,常见的有SVN/CVS/GitHut等...通过它们 ...

  4. this指针与function变量--this究竟指向哪里?

    参考文章:<深入浅出 JavaScript 中的 this> http://www.ibm.com/developerworks/cn/web/1207_wangqf_jsthis/ Ja ...

  5. Flink资料(3)-- Flink一般架构和处理模型

    Flink一般架构和处理模型 本文翻译自General Architecture and Process Model ----------------------------------------- ...

  6. 在Windows的CMD中如何设置支持UTF8编码

    这个问题很多人开始都会不知道,当然包括曾经的我,当用到的时候,只好求助于伟大的股沟和度娘了.网上有设置的方法,但说明确不够详细系统,说设置字体为:Lucida Console.问题是,在默认方式下,只 ...

  7. VS Code调试.NET Core

    VS Code调试.NET Core应用遇到的坑 为什么会有”坑“ 博客园里有好多介绍怎么使用VS Code以及调试.NET Core的文章,但是都是基于直接构建Asp.Net Core Mvc单项目 ...

  8. J2SE知识点摘记(九)

    1.         线程操作的一些方法 方法名称              方法说明 public static int activeCount()             返回线程组中目前活动的线 ...

  9. 你会用shuffle打乱列表吗?

    在网站上我们经常会看到关键字云(Word Cloud)和标签云(Tag Cloud),用于表明这个关键字或标签是经常被查阅的,而且还可以看到这些标签的动态运动,每次刷新都会有不一样的关键字或便签,让浏 ...

  10. iOS开发之主题皮肤

    iOS开发之主题皮肤 分类: [iOS]  最近在开发一款[公交应用],里面有个模块涉及到主题设置,这篇文章主要谈一下个人的做法. 大概的步骤如下: (1):整个应用依赖于一个主题管理器,主题管理器根 ...