Foundation 框架請允許你利用文件系統對文件或目錄執行基本操作。這些基本操作是由NSFileManager類提供的,
這個類的方法具有如下功能:
- 創建 一個新文件
- 從現有文件中讀取數據
- 將數據寫入文件中
- 重新命名文件
- 刪除文件
- 測試文件是否存在
- 確定文件的大小及其他屬性
- 複製文件
- 測試兩個文件的內容是否相同
上述多數據操作也可以直接對目錄進行。例如,可以創建目錄,讀取其中的內容,或者刪除目錄。
管理文件和目錄
每個文件方法都是對NSFileManager對象的調用,而NSFileManager對象 是通過向類發送一條defaultManager消息創建的,
如下所示:
NSFileManager *fm
...
fm = [NSFileManager defaultManager];
例如,要從當前目錄刪除名爲todolist的文件,首先要創建一個NSFileManager對象(如前面所示),然後調用removeFileAtPath方法,
代碼如下:
[fm removeFileAtPath: @"todolist" handler:nil];
可以測試返回結果,以確保文件刪除:
if([fm removeFileAtPath:@"todolist" handler:nil] == NO)
{
NSLog(@"Couldn't remove file todolist");
return 1;
}
下面是一個基本文件操作的例子:
- //Basic ifle operations
- //Assumes the existence of a file called "testfile"
- //in ther current working directory
- #import <Foundation/NSObject.h>
- #import <Foundation/NSString.h>
- #import <Foundation/NSFileManager.h>
- #import <Foundation/NSAutoreleasePool.h>
- #import <Foundation/NSDictionary.h>
- int main(int argc, const char *argv[])
- {
- NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
- NSString *fName = @"testfile.txt";
- NSFileManager *fm;
- NSDictionary *attr;
- //Need to create an instance of the file manager
- fm = [NSFileManager defaultManager];
- //Let's make sure our test file exists first
- if([fm fileExistsAtPath: fName] == NO)
- {
- NSLog(@"File doesn't exist'");
- return 1;
- }
- //Now let's make a copy
- if([fm copyPath: fName toPath: @"newfile.txt" handler:nil] == NO)
- {
- NSLog(@"File copy failed");
- return 2;
- }
- //Let's test to see if the two files are identical
- if([fm contentsEqualAtPath: fName andPath: @"newfile.txt"] == NO)
- {
- NSLog(@"Files are not equal!");
- return 3;
- }
- //Now let's rename the copy
- if([fm movePath: @"newfile.txt" toPath: @"newfile2.txt" handler:nil] == NO)
- {
- NSLog(@"File rename failed!");
- return 4;
- }
- //Get the size of newfile2
- if((attr = [fm fileAttributesAtPath: @"newfile2.txt" traverseLink:NO]) == nil)
- {
- NSLog(@"Couldn't get file attributes!");
- return 5;
- }
- NSLog(@"File size is %i bytes",[[attr objectForKey: NSFileSize] intValue]);
- //And finally, let's delete the original file
- if([fm removeFileAtPath: fName handler:nil] == NO)
- {
- NSLog(@"File removal failed!");
- return 6;
- }
- NSLog(@"All operations were successful!");
- //Display the contents of the newly-created file
- NSLog(@"%@",[NSString stringWithContentsOfFile:@"newfile2.txt" encoding:NSUTF8StringEncoding error:nil]);
- [pool drain];
- return 0;
- }
使用NSData類
使用文件時,需要頻繁地將數據讀入一個臨時存儲區,它通常稱爲緩衝區。當收集數據,以便隨後將這些數據輸出到文件中時,
通常也使用存儲區。Foundation的NSData類提供了一種簡單的方式,它用來設置緩衝 區、將文件的內容讀入緩衝區,或將
緩衝區的內容寫到一個文件。
下面是一個使用NSData 的例子:
- #import <Foundation/NSObject.h>
- #import <Foundation/NSString.h>
- #import <Foundation/NSFileManager.h>
- #import <Foundation/NSAutoreleasePool.h>
- #import <Foundation/NSData.h>
- //make a copy of file
- int main(int argc, const char *argv[])
- {
- NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
- NSFileManager *fm;
- NSData *fileData;
- fm = [NSFileManager defaultManager];
- //Read the file newfile2
- fileData = [fm contentsAtPath: @"newfile2.txt"];
- if(fileData == nil)
- {
- NSLog(@"File read failed!");
- return 1;
- }
- //Write the data to newfile3
- if([fm createFileAtPath: @"newfile3.txt" contents: fileData attributes:nil] == NO)
- {
- NSLog(@"Couldn't create the copy!");
- return 2;
- }
- NSLog(@"File copy was successful!");
- [pool drain];
- return 0;
- }
使用目錄
NSFileManager類中,還有很多操作目錄的方法。
下面是一個例子:
- #import <Foundation/NSObject.h>
- #import <Foundation/NSString.h>
- #import <Foundation/NSFileManager.h>
- #import <Foundation/NSAutoreleasePool.h>
- int main(int argc, const char *argv[])
- {
- NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
- NSFileManager *fm;
- NSString *dirName = @"testdir";
- NSString *path;
- fm = [NSFileManager defaultManager];
- //Get current directory
- path = [fm currentDirectoryPath];
- NSLog(@"Current directory path is %@",path);
- //Create a new directory
- if([fm createDirectoryAtPath: dirName attributes: nil] == NO)
- {
- NSLog(@"Couldn't create directory!");
- return 1;
- }
- //Rename the new directory
- if([fm movePath: dirName toPath: @"newdir" handler: nil] == NO)
- {
- NSLog(@"Directory rename failed!");
- return 2;
- }
- //Change directory into the new directory
- if([fm changeCurrentDirectoryPath: @"newdir"] == NO)
- {
- NSLog(@"Change directory failed!");
- return 3;
- }
- //Now get and display current working directory
- path = [fm currentDirectoryPath];
- NSLog(@"Current directory path is %@ ",path);
- NSLog(@"All operations were successful!");
- [pool drain];
- return 0;
- }
枚舉目錄中的內容
有時需要枚舉目錄是的內容,就需要用到enumeratorAtPath:方法或者directoryContentsAtPath: 方法,來完成枚舉過程。
如果使用第一種方法,一次可以枚舉指定目錄中的每個文件,默認情況下,如果其中一個文件爲目錄,那麼也會遞歸枚舉它的內容。
在這個過程中,通過向枚舉對象發送一條skipDescendants消息,可以動態的地阻止遞歸過程,從而不再枚舉目錄中的內容。
對於directoryContentsAtPath:方法,使用這個方法,可心枚舉指定目錄的內容,並在一個數組中返回文件列表。
如果這個目錄中的任何文件本身是個目錄,這個方法並不遞歸枚舉它的內容。
下面一個例子是這兩個方法的使用:
- #import <Foundation/NSArray.h>
- #import <Foundation/NSString.h>
- #import <Foundation/NSFileManager.h>
- #import <Foundation/NSAutoreleasePool.h>
- //enumeratorAtPath:方法和directoryContentsAtPath:方法
- //的區別是:前者遍歷子目錄,後者不遍歷子目錄
- int main(int argc, const char *argv[])
- {
- NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
- NSFileManager *fm;
- NSString *path;
- NSDirectoryEnumerator *dirEnum;
- NSArray *dirArray;
- fm = [NSFileManager defaultManager];
- //Get current directory path
- path = [fm currentDirectoryPath];
- //Enumerate the directory
- dirEnum = [fm enumeratorAtPath:path];
- NSLog(@"Contents of %@: ",path);
- while((path = [dirEnum nextObject]) != nil)
- NSLog(@"%@",path);
- //Another way to enumerate a directory
- dirArray = [fm directoryContentsAtPath:[fm currentDirectoryPath]];
- NSLog(@"Contents using directoryContentsAtPath:");
- for(int i = 0; i < [dirArray count];i++)
- {
- NSLog(@"%@",[dirArray objectAtIndex: i]);
- }
- [pool drain];
- return 0;
- }
使用路徑:NSPathUtilities.h
NSPathUtilities.h包含了NSString的函數和分類擴展,它允許你操作路徑名。
牛逼 作者 :