天天看點

iOS開發代碼:從文本檔案中讀取内容到字元串裡

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);

版權聲明:本文為CSDN部落客「weixin_33700350」的原創文章,遵循CC 4.0 BY-SA版權協定,轉載請附上原文出處連結及本聲明。

原文連結:https://blog.csdn.net/weixin_33700350/article/details/92010949