一 目錄說明
如下圖所示,一個沙盒中典型存在下面的目錄和文件
各個目錄及文件說明:
1.Documents 您應該將所有的應用程序數據文件寫入到這個目錄下,這個目錄用於存儲用戶數據或其它應該定期備份的信息。
2.AppName.app
這是應用程序的程序包目錄,包含應用程序的本身。由於應用程序必須經過簽名,所以您在運行時不能對這個目錄中的內容進行修改,否則可能會使應用程序無法啟動。
3.Library
vc3Ryb25nPiAgICAgICAgICDV4rj2xL/CvM/C09DBvbj219PEv8K8o7pDYWNoZXMgus0gUHJlZmVyZW5jZXMKCiAKICAgPGVtPlByZWZlcmVuY2VzPC9lbT4gICAgICCw/Lqs06bTw7PM0PK1xMarusPJ6NbDzsS8/qGjxPqyu9OmuMPWsb3TtLS9qMarusPJ6NbDzsS8/qOstvjKx9OmuMPKudPDTlNVc2VyRGVmYXVsdHPA4MC0yKG1w7rNyejWw9Om08OzzNDytcTGq7rDCgogCiAgICA8ZW0+Q2FjaGVzIDwvZW0+xL/CvNPD09q05rfF06bTw7PM0PLXqNPDtcTWp7PWzsS8/qOssaO05tOm08OzzNDy1Nm0zsb0tq+5/bPM1tDQ6NKqtcTQxc+ioaMKCjxzdHJvbmc+NC50bXA8L3N0cm9uZz4gICAKICAgICAgICAgICAgICAg1eK49sS/wrzTw9PatOa3xcHZyrHOxLz+o6yxo7Tm06bTw7PM0PLU2bTOxvS2r7n9s8zW0LK70OjSqrXE0MXPoqGjCgo8YnI+CgoK16LS4qO6MS5pVHVuZXPU2tPraVBob25lzayyvcqxo6yxuLfdy/nT0LXERG9jdW1lbnRzus1MaWJyYXJ5zsS8/qGjCgogICAgICAgICAgMi5pUGhvbmXU2tbYxvTKsaOsu+G2qsb6y/nT0LXEdG1wzsS8/qGjCgo8YnI+CgoKPHN0cm9uZz62/iDJs7rQ1tDOxLz+vNC6zc7EvP6y2df3PC9zdHJvbmc+Cgo8YnI+CgoKPHN0cm9uZz7KtcD9tPrC69K7OsHQs/bP4NOmtcTEv8K8PC9zdHJvbmc+CgotICh2b2lkKSBmaWxlT3BlcmF0aW9uPGJyPgoKewoKICAgIC8vybO60Mv51Nq1xLj5xL/CvDxicj4KICAgIE5TU3RyaW5nICpob21lRGlyZWN0b3J5ID0gTlNIb21lRGlyZWN0b3J5KCk7PGJyPgogICAgTlNMb2coQA==”path:%@”, homeDirectory);
//應用程序路徑
NSString*appPath = [[NSBundle mainBundle] resourcePath];
NSLog(@”path:%@”,
appPath);
//document目錄
NSArray *docPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPaths = [docPaths objectAtIndex:0];
NSLog(@”path:%@”, documentPaths);
//Cache目錄
NSArray *cacPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachePath = [cacPaths objectAtIndex:0];
NSLog(@”%@”, cachePath);
//獲取Library目錄
NSArray *libPaths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *libraryPath = [libPaths objectAtIndex:0];
NSLog(@”%@”, libraryPath);
//獲取Tmp目錄
NSString *tmpDir = NSTemporaryDirectory();
NSLog(@”%@”, tmpDir);
}
輸出結果:
2014-04-23 14:55:35.621 ZZFile[12523:70b] path:/Users/XXXXXX/Library/Application Support/iPhone Simulator/7.0.3/Applications/9170019F-379C-42C3-96E2-848CE9268FEF
2014-04-23 14:55:35.623 ZZFile[12523:70b] path:/Users/XXXXXX/Library/Application Support/iPhone Simulator/7.0.3/Applications/9170019F-379C-42C3-96E2-848CE9268FEF/ZZFile.app
2014-04-23 14:55:35.624 ZZFile[12523:70b] path:/Users/XXXXXX/Library/Application Support/iPhone Simulator/7.0.3/Applications/9170019F-379C-42C3-96E2-848CE9268FEF/Documents
2014-04-23 14:55:35.626 ZZFile[12523:70b] /Users/XXXXXX/Library/Application Support/iPhone Simulator/7.0.3/Applications/9170019F-379C-42C3-96E2-848CE9268FEF/Library/Caches
2014-04-23 14:55:35.631 ZZFile[12523:70b] /Users/XXXXXX/Library/Application Support/iPhone Simulator/7.0.3/Applications/9170019F-379C-42C3-96E2-848CE9268FEF/Library
2014-04-23 14:55:35.632 ZZFile[12523:70b] /Users/XXXXXX/Library/Application Support/iPhone Simulator/7.0.3/Applications/9170019F-379C-42C3-96E2-848CE9268FEF/tmp/
實例代碼二:文件讀寫
– (void) WRFile
{
//寫入數據
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
if (!docDir)
{
NSLog(@”Documents 目錄未找到”);
}
NSArray *array = [[NSArray alloc] initWithObjects:@”Hebie”,@”BJUT”,nil];
NSString *filePath = [docDir stringByAppendingPathComponent:@”zz.text”];
[array writeToFile:filePath atomically:YES];
//讀取數據
// NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
// NSString *docDir = [paths objectAtIndex:0];
// NSString *filePath = [docDir stringByAppendingPathComponent:@”testFile.txt”];
NSArray *result = [[NSArray alloc]initWithContentsOfFile:filePath];
NSLog(@”%@”, result);
}
– (void) userDefalut
{
NSUserDefaults *defalut = [NSUserDefaults standardUserDefaults];
[defalut setObject:@”ZZBJUT” forKey:@”name”];
[defalut setObject:[NSNumber numberWithInteger:25] forKey:@”age”];
[defalut synchronize];
defalut = nil;
defalut = [NSUserDefaults standardUserDefaults];
NSString *name = [defalut objectForKey:@”name”];
NSInteger age = [[defalut objectForKey:@”age”] integerValue];
NSLog(@”name:%@ age:%d”,name ,age);
}
輸出結果:
2014-04-23 14:01:11.559 ZZFile[12104:70b] (
Hebie,
BJUT
)
2014-04-23 14:01:11.855 ZZFile[12104:70b] name:ZZBJUT age:25
沙盒中的Documents目錄中多瞭一個zz.text
另外在Library的Preferences目錄中多瞭一個 com.qiniudn.zhangzhe.ZZFile.plist文件
如下圖所示:
打開com.qiniudn.zhangzhe.ZZFile.plist文件裡面是我們用NSUserDefault保存的數據。
打開zz.txt文件
Hebie
BJUT
可以看到文件中的數據使用屬性列表的格式進行存儲
使用如下代碼刪除文件:
//刪除文件
if ([[NSFileManager defaultManager] fileExistsAtPath:finalLocation])
{
retVal = [[NSFileManager defaultManager] removeItemAtPath:finalLocation error:NULL];
NSLog(@”delete
file:%@”,finalLocation);
}
實例代碼三:文件夾操作
– (void)createFolder:(NSString *)createDir
{
BOOL isDir = NO;
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL existed = [fileManager fileExistsAtPath:createDir isDirectory:&isDir];
if ( !(isDir == YES && existed == YES) )
{
[fileManager createDirectoryAtPath:createDir withIntermediateDirectories:YES attributes:nil error:nil];
}
}
– (void) folderOperation
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; //
Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@”first”];
[self createFolder:dataPath];
dataPath = [dataPath stringByAppendingPathComponent:@”secode”];
[self createFolder:dataPath];
//創建文件
NSString *testPath = [dataPath stringByAppendingPathComponent:@”zz.txt”];
NSString *string = @”ZZBJUT 寫入文件”;
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager createFileAtPath:testPath
contents:[string dataUsingEncoding:NSUTF8StringEncoding]
attributes:nil];
dataPath = [dataPath stringByAppendingPathComponent:@”third”];
[self createFolder:dataPath];
}
沙盒中的內容如下,可以看到在document目錄中創建/first/second/third目錄,並且在
seconde中創建瞭一個zz.text文件。
實例代碼四:拷貝app目錄中的文件到Document中
– (void) copyBundleFileToDocument
{
NSString *flieName = @”apple.jpg”;
NSString *fileToCopy = [[NSBundle mainBundle] pathForResource:@”apple.jpg” ofType:nil];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; //
Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingString:@”/first/second/third”];
NSString * finalLocation = [dataPath stringByAppendingPathComponent:flieName];
BOOL retVal = YES; // If the file already exists, we’ll return
success…
if (![[NSFileManager defaultManager] fileExistsAtPath:finalLocation])
{
retVal = [[NSFileManager defaultManager] copyItemAtPath:fileToCopy
toPath:finalLocation
error:NULL];
NSLog(@”copy done!”);
NSLog(@”souce:%@”,fileToCopy);
NSLog(@”destination:%@”,finalLocation);
}
}
輸出結果:
2014-04-23 14:15:35.262 ZZFile[12218:70b] copy done!
2014-04-23 14:15:35.265 ZZFile[12218:70b] souce:/Users/XXXXXX/Library/Application Support/iPhone Simulator/7.0.3/Applications/9170019F-379C-42C3-96E2-848CE9268FEF/ZZFile.app/apple.jpg
2014-04-23 14:15:35.266 ZZFile[12218:70b] destination:/Users/XXXXXX/Library/Application Support/iPhone Simulator/7.0.3/Applications/9170019F-379C-42C3-96E2-848CE9268FEF/Documents/first/second/third/apple.jpg
如下圖所示我們將app目錄中的apple.jgp文件拷貝到瞭Documents的third文件夾中
註意:
NSBundle是一個目錄,其中包含瞭程序使用到的資源,包含瞭如圖像、聲音、編譯好的代碼、nib文件(用戶也會把bundle稱為plug-in)等。對應bundle,cocoa提供瞭類NSBundle.
Bundle其實是一種對應用程序的打包方式,就像java中的jar文件一樣。NSBundle是對bundle的一種抽象表示,使用它可以便捷的訪問應用程序中的資源。
上面代碼中用NSBundle獲取程序裡的一張圖片apple.jpg,根據輸出的結果圖片的路徑為:
/Users/XXXXXX/Library/Application
Support/iPhone Simulator/7.0.3/Applications/9170019F-379C-42C3-96E2-848CE9268FEF/ZZFile.app/apple.jpg
實例代碼五:列出目錄內容
– (void) listFile
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSFileManager *fileManage = [NSFileManager defaultManager];
NSArray *file = [fileManage subpathsOfDirectoryAtPath: documentsDirectory error:nil];
NSLog(@”%@”,file);
}
輸出內容:
2014-04-23 14:31:24.881 ZZFile[12334:70b] (
“.DS_Store”,
first,
“first/.DS_Store”,
“first/second”,
“first/second/.DS_Store”,
“first/second/third”,
“first/second/third/apple.jpg”,
“first/second/zz.txt”,
“zz.text”
)
實例代碼六:混合數據的讀寫
– (void) writeMixData
{
NSString * fileName = @”mixtypedata.txt”;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//獲取文件路徑
NSString *path = [documentsDirectory stringByAppendingPathComponent:fileName];
//待寫入的數據
NSString *temp = @”Hello world!”;
int dataInt = 1234;
float dataFloat = 3.14f;
//創建數據緩沖
NSMutableData *writer = [[NSMutableData alloc] init];
//將字符串添加到緩沖中
[writer appendData:[temp dataUsingEncoding:NSUTF8StringEncoding]];
//將其他數據添加到緩沖中
[writer appendBytes:&dataInt length:sizeof(int)];
[writer appendBytes:&dataFloat length:sizeof(float)];
//將緩沖的數據寫入到文件中
[writer writeToFile:path atomically:YES];
//[self readMixData];
}
– (void) readMixData
{
NSString * fileName = @”mixtypedata.txt”;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//獲取文件路徑
NSString *path = [documentsDirectory stringByAppendingPathComponent:fileName];
//讀取數據:
int intData;
float floatData = 0.0;
NSString *stringData;
NSData *reader = [NSData dataWithContentsOfFile:path];
stringData = [[NSString alloc] initWithData:
[reader subdataWithRange:NSMakeRange(0, [@”Hello
world!” length])]
encoding:NSUTF8StringEncoding];
[reader getBytes:&intData range:NSMakeRange([@”Hello
world!”length], sizeof(int))];
[reader getBytes:&floatData range:NSMakeRange([@”Hello
world!” length] + sizeof(int), sizeof(float))];
NSLog(@”stringData:%@ intData:%d floatData:%f”, stringData, intData, floatData);
}
輸出結果:
2014-04-23 14:44:53.820 ZZFile[12452:70b] stringData:Hello world! intData:1234 floatData:3.140000
註意:當字符串中有中文的時候會出現亂碼,因為[temp length]算長度是,把中文算成一位瞭,出來的結果有誤。
三 文件操作封裝
封裝類ZZFile
頭文件ZZFile.h 如下:
@interface ZZFile
: NSObject
//Get Home/Bundle/Document/Library/Cache/Temp Directory
+ (NSString*) HomeDirectory;
+ (NSString*) BundleDirectory;
+ (NSString*) DocumentDirectory;
+ (NSString*) LibraryDirectory;
+ (NSString*) LibraryCacheDirectory;
+ (NSString*) TempDirectory;
//File Path.
+ (NSString *) DocumentFilePath:(NSString *) fileName;
+ (BOOL) FileIsExist:(NSString*) fileName;
+ (BOOL) DocumentFileIsExist:(NSString*) fileName;
//File Operation.
+ (BOOL) WriteObject:(id) object filePath:(NSString*)
fileName;
+ (BOOL) WriteObject:(id) object DocumentFilePath:(NSString *)fileName;
+ (BOOL) removeFileAtPath:(NSString*) fileName;
+ (BOOL) removeDocumentFileAtPath:(NSString *)fileName;
+ (BOOL) RenameDocumentFile:(NSString*) oldName forName:(NSString*)
newName;
+ (BOOL) CopyDocumentFileFrom:(NSString*) source To:(NSString*)destination;
//Folder Operation.
+ (BOOL) CreateDocumentFolder:(NSString*) folderName;
+ (BOOL) RemoveDocumentFolder:(NSString*) folderName;
+ (BOOL) RenameDocumentFolder:(NSString*) oldName forName:(NSString*)
newName;
+ (BOOL) CopyDocumentFolderFrom:(NSString*) source To:(NSString*)destination;
+ (NSArray*) TraverseDocumentFolder:(NSString*) folderName;
//Copy Bundle file To Document
+ (BOOL) CopyBundleFile:(NSString*) fileName ToDocument:(NSString*)
documentFileName;
//NSUserDefalut
+ (void) UserDefalutObject:(id)object forKey:(NSString*)
key;
+ (id) UserDefalutObjectForKye:(NSString*) key;
+ (void) Synchronize;
//Hash File
+ (NSString *) md5HashOfFileAtPath:(NSString *) filePath;
+ (NSString *) sha1HashOfFileAtPath:(NSString *) filePath;
+ (NSString *) sha512HashOfFileAtPath:(NSString *) filePath;
@end
詳見github: https://github.com/ZhangzheBJUT/IOSProject/tree/master/FiltTool
ZZFile.h和ZZFile.m是對文件操作的簡單封裝,方便文件的存取修改。