讀取本地文件

NSError *error;

  NSString *textFileContents = [NSString

  stringWithContentsOfFile:[[NSBundle mainBundle]

  pathForResource:@”myTextFile”

  ofType:@”txt”]

  encoding:NSUTF8StringEncoding

  error: & error];

  // If there are no results, something went wrong

  if (textFileContents == nil) {

  // an error occurred

  NSLog(@”Error reading text file. %@”, [error localizedFailureReason]);

  }

  NSArray *lines = [textFileContents componentsSeparatedByString:@””];

  NSLog(@”Number of lines in the file:%d”, [lines count] );

[IOS]讀取本地文件內容

NSString*filePath=[[NSBundlemainBundle] pathForResource:@”1”ofType:@”txt”];

NSString*str=[[NSStringalloc] initWithContentsOfFile:filePath];
NSLog(@”%@”,str);

通過 NSHomeDrietory獲取文件路徑

NSString *homeD = NSHomeDrietory();//獲取Home路徑

NSString *fileD = [homeD stringByAppendingPathComponent:@”temp/xxx.xxx”];

這樣可以獲取xxx的完整路徑了


使用NSSearchPathForDirectoriesInDomains獲取指定路徑

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

NSString *documentsDirectory = [paths objectAtIndex:0];需要的路徑

NSString *fileD = [documentSDirectory stringByAppendingPathComponent:@”xxx.txt”];


NSSearchPathForDirectoriesInDomains具體檢索一個子文件夾

NSDocumentDirectory 這個是個常量根類中的枚舉變量吧,代表要查找的路徑document

也可以使用NSCachesDirectory書名路徑爲Caches

NSUserDomainMask 這個指定了文件的檢索範圍只在沙箱內部

最後YES指定了是否展開波浪線;在MAC系統中 ~代表主路徑 (Home) 如果不展開 路徑就如 ~/Document 如果展開就是完整的路徑 一般都設爲YES


使用NSTemportryDirectory獲取臨時文件的全路徑

NSString * temD = NSTemportryDirectory();

NSString *fileD = [temD stringByAppendingPathComponent:@”xxx.txt”];

NSLog(@”%@”,temD);

創建新文件

-(BOOL)createFileAtPath:(NSString*)path contents:(NSData*)data attributes:(NSDictionary *)attr;

要創建文件夾第一個參數就是他的全路徑了,第二個是文件的內容,最後一個文件的屬性

返回值爲創建成功與失敗

創建路徑

-(Void)createDirectoryAtPath:(NSString *)path attributes:(NSDictionary)attr;

創建路徑跟文件差不多

刪除文件

-(BOOL)removeFileAtPath:(NSString*)path handler:(id)handler;

調用刪除文件的函數需要指定全路徑 並且制定handler來執行flieManager : willProcessPath和fileManager:shouldProceedAfterError回調函數 也可以吧handler置爲nil這樣刪除文件出錯的時候會終止操作 並返回NO

寫入數據:

//獲取文件路徑

NSString *path = [documentsDirectory stringByAppendingPathComponent:@”fileName”];

NSString *temp = @”Hello world”;

int a=1;

//創建數據緩衝

NSMutableData *writer = [[NSMutableData alloc] init];

//將字符串添加到緩衝中

[writer appendData:[temp dataUsingEncoding:NSUTF8StringEncoding]];

//將其他數據添加到緩衝中

[writer appendBytes:&a length:sizeof(a)];

//將緩衝的數據寫入到文件中

[writer writeToFile:path atomically:YES];

[writer release];

讀取數據:

int a;

Float b;

NSString *str;

NSData *reader = [NSData dataWithContentsOfFile:path];

str = [[NSString alloc] initWithData:[reader subdataWithRange:NSMakeRange(0, [temp length])]

encoding:NSUTF8StringEncoding];

[reader getBytes:&a range:NSMakeRange([temp length], sizeof(a)];

[reader getBytes:&str range:NSMakeRange([temp length] + sizeof(a), sizeof(b))];

NSLog(@”a:%@ b:%i str:%f”, a, b, str);

讀取工程中的文件:

讀取數據時,要看待讀取的文件原有的文件格式,是字節碼還是文本,我經常需要重文件中讀取字節碼,所以我寫的是讀取字節文件的方式。

//用於存放數據的變量,因爲是字節,所以是UInt8

UInt8 b = 0;

//獲取文件路徑

NSString *path = [[NSBundle mainBundle] pathForResource:@”fileName” ofType:@”“];

//獲取數據

NSData *reader = [NSData dataWithContentsOfFile:path];

//獲取字節的個數

int length = [reader length];

NSLog(@”——->bytesLength:%d”, length);

for(int i = 0; i < length; i++)

{

//讀取數據

[reader getBytes:&b range:NSMakeRange(i, sizeof(b))];

NSLog(@”——–>data%d:%d”, i, b);

}

實例

@implementation ManagerFile

-(void)writeFile:(NSString *)file{

 //創建文件管理器     

 NSFileManager *fileManager = [NSFileManager defaultManager];     

 //獲取路徑     

 //參數NSDocumentDirectory要獲取那種路徑     

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

 NSString *documentsDirectory = [paths objectAtIndex:0];//去處需要的路徑         

 //更改到待操作的目錄下     

 [fileManager changeCurrentDirectoryPath:[documentsDirectory stringByExpandingTildeInPath]];     

 //創建文件fileName文件名稱,contents文件的內容,如果開始沒有內容可以設置爲nil,attributes文件的屬性,初始爲nil     

 //獲取文件路徑     

 [fileManager removeItemAtPath:@"username" error:nil];     

 NSString *path = [documentsDirectory stringByAppendingPathComponent:@"username"];     

  //創建數據緩衝     NSMutableData *writer = [[NSMutableData alloc] init];     

  //將字符串添加到緩衝中     

  [writer appendData:[file dataUsingEncoding:NSUTF8StringEncoding]];     

  //將其他數據添加到緩衝中     

  //將緩衝的數據寫入到文件中     

  [writer writeToFile:path atomically:YES];     

  [writer release];

}

-(NSString *)readFile{

 //創建文件管理器     

  NSFileManager *fileManager = [NSFileManager defaultManager];     

  //獲取路徑     

  //參數NSDocumentDirectory要獲取那種路徑     

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

 NSString *documentsDirectory = [paths objectAtIndex:0];//去處需要的路徑         

 //更改到待操作的目錄下     

 [fileManager changeCurrentDirectoryPath:[documentsDirectory stringByExpandingTildeInPath]];     

  //獲取文件路徑     

  NSString *path = [documentsDirectory stringByAppendingPathComponent:@"username"];     

  NSData *reader = [NSData dataWithContentsOfFile:path];     

  return [[NSString alloc] initWithData:reader                                  encoding:NSUTF8StringEncoding];

}

@end

對一個文件重命名

  想要重命名一個文件,我們需要把文件移到一個新的路徑下 。下面的代碼創建了我們所期望的目標文件的路徑,然後請求移動文件以及在移動之後顯示文件目錄 。

//通過移動該文件對文件重命名

NSString *filePath2= [documentsDirectory

stringByAppendingPathComponent:@”file2.txt”];

//判斷是否移動

if ([fileMgr moveItemAtPath:filePath toPath:filePath2 error:&error] != YES)

NSLog(@”Unable to move file: %@”, [error localizedDescription]);

//顯示文件目錄的內容

NSLog(@”Documentsdirectory: %@”,

[fileMgr contentsOfDirectoryAtPath:documentsDirectoryerror:&error]);


獲取一個目錄內的文件及文件夾列表 。

NSFileManager *fileManager = [NSFileManager defaultManager];

//在這裏獲取應用程序Documents文件夾裏的文件及文件夾列表

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

    NSString *documentDir = [documentPaths objectAtIndex:0];  

    NSError *error = nil;  

    NSArray *fileList = [[NSArray alloc] init];  

//fileList便是包含有該文件夾下所有文件的文件名及文件夾名的數組

    fileList = [fileManager contentsOfDirectoryAtPath:documentDir error:&error];  

以下這段代碼則可以列出給定一個文件夾裏的所有子文件夾名

NSMutableArray *dirArray = [[NSMutableArray alloc] init];

    BOOL isDir = NO;  

//在上面那段程序中獲得的fileList中列出文件夾名

    for (NSString *file in fileList) {  

            NSString *path = [documentDir stringByAppendingPathComponent:file];  

            [fileManager fileExistsAtPath:path isDirectory:(&isDir)];  

            if (isDir) {  

                    [dirArray addObject:file];  

            }  

            isDir = NO;  

    }  

    NSLog(@"Every Thing in the dir:%@",fileList);  

    NSLog(@"All folders:%@",dirArray);

感謝博主的分享:
http://my.oschina.net/u/615517/blog/196042

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章