본문 바로가기
ios 뽀개기/objective-c

iOS 파일 시스템 관련 함수들 (NSFileManager Class)

by 인생여희 2018. 10. 23.
반응형


iOS 파일 시스템 관련 함수들 (NSFileManager Class)

디렉토리 다루기

method explanation

- (NSString *) currentDirectoryPath 현재 경로를 가져온다.

- (BOOL) changeCurrentDirectoryPath:path 현재 경로를 변환한다.

- (BOOL) createDirectoryAtPath 새 디렉토리 생성한다.

- (BOOL) copyPath:from toPath:to handler : handler 디렉토리 구조를 복사한다.

- (BOOL) fileExistsAtPath : path isDirectory:(BOOL *)flag 파일이 디렉토리인지 구분한다.

- (NSArray *) directoryContentsAtPath:path 디렉토리 내용을 가져온다.

- (NSDirectoryEnumerator *) enumeratorAtPath : path 디렉토리 내용을 가져온다.

- (BOOL) removeFileAtPath : path handler : handler 빈 디렉토리를 삭제한다.

- (BOOL) movePath : path toPath : to handler : handler 디렉토리 이름을 변경 하거나 옮긴다.

파일 다루기

method explanation

- (NSData) contentsAtPath 파일에서 데이터를 읽는다.

- (BOOL) createFileAtPath : path contents:(NSData*) data attributes:attr 파일에 데이터를 기록한다.

- (BOOL) removeFileAtPath : path handler:handler 파일을 삭제한다.

- (BOOL) movePath : from toPath : to Handler : handler 파일의 이름을 변경하거나 위치를 변경한다.

- (BOOL) copyPath : from toPath : to Handler:handler 파일을 복사한다.

- (BOOL) contentsEqualAtPath: path1 andPath: path2 두파일의 내용을 비교한다.

- (BOOL) fileExistsAtPath:path 파일이 존재하는지를 확인한다.

- (BOOL) isReadableFileAtPath:path 파일이 있고, 읽을수 있는지 확인한다.

- (BOOL) isWritableFileAtPath:path 파일이 있고, 기록 가능한지 확인한다.

- (NSDictionary *) fileAttributesAtPath: path traverseLink:(BOOL)flag 파일 속성을 가져온다.

- (BOOL) changeFileAttributes:attr atPath:path 파일 속성을 변환한다.

NSFileHandle

파일의 내용을 조작하기 위한 클래스.

모든 파일은 미리 존재한다고 가정한다.

파일을 생성하기 위해서는 NSFileManaer을 사용한다.

기본적인 메소드

* 클래스 메소드

+ fileHandleForReadingAtPath;

+ fileHandleForWritingAtPath;

+ fileHandleForUpdatingAtPath;

* 인스턴스 메소드

- availableData;

- readDataToEndOfFile;

- readDataOfLength;

- writeData;

- offsetInFile;

- seekToFileOffset;

- seekToEndOfFile;

- truncateFileAtOffset;


- closeFile


출처: http://ain7.tistory.com/entry/iOS-파일-시스템-관련-함수들-NSFileManager-Class [용용 블로그]



참고: 

https://medium.com/@Alpaca_iOSStudy/has-recommended

http://yoogomja.tistory.com/entry/NSString%EC%9D%84-%ED%8C%8C%EC%9D%BC%EB%A1%9C-%EC%9D%BD%EA%B3%A0-%EC%93%B0%EA%B8%B0

http://wjapps.com/xe/Objective_C/1203



참고소스 : divce 와 simulator와 경로 다름. 체크하기.



        //파일매니져 생성

        NSFileManager *fileManager = [NSFileManager defaultManager];

        

        //현재 파일 위치

        NSString *currentPath = [fileManager currentDirectoryPath];

        

        NSLog(@"currentPath : %@ " , currentPath);

        

        //DocumentationDirectory 경로

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

        NSLog(@"paths : %@ " , paths[0]);

        NSString *path = paths[0];

        

        //파일 루트 변경하기

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

        currentPath = [fileManager currentDirectoryPath];

        NSLog(@"cpathfile : %@ " , currentPath);


        

        //디렉토리 생성하기

        NSError *error = nil;

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

        if ([fileManager createDirectoryAtPath:newDir withIntermediateDirectories:YES attributes:nil error:&error] == NO){

            NSLog(@"생성실패");

        } else {

            NSLog(@"생성성공 : currentPath : %@ " , currentPath);

        }

        

        

        //디렉토리가 존재하는지 확인

        if([fileManager isWritableFileAtPath:@"/Users/Shared/NewDirectory1"]){

            

            NSLog(@"생성확인");

        }else{

            NSLog(@"생성확인 안됨");

        }

     

        NSError *err = nil;

        NSString *logPath = @"/Users/Shared/NewDirectory1/log.txt";

        // 2. 기존에 생성할 파일이 존재하는지 확인

        if([fileManager fileExistsAtPath:logPath]){

            // 파일이 존재하는 경우

            

            // 기존에 있던 파일의 내용을 불러와 뒤에 덧붙임

            NSString *logStr = [NSString stringWithFormat:@"로그 내용: 기존에 파일이 존재해서..."];

            NSMutableString *fileStr = [NSMutableString stringWithContentsOfFile:logPath encoding:NSUTF8StringEncoding error:nil];

            

            // 기존 파일에서 글 내용을 읽어옴

            // 읽어올때 에러처리 생략 !

            [fileStr appendFormat:@"%@",logStr];

            NSLog(@"fileStr : %@", fileStr);

            

            

            if([logStr writeToFile:logPath atomically:FALSE encoding:NSUTF8StringEncoding error:&err]){

                NSLog(@"Log Create!1");

            }

            else{

                NSLog(@"Log Create Err1 : %@",err);

            }

        }

        else{

            // 파일이 존재하지 않는 경우

            NSString *logStr = [NSString stringWithFormat:@"로그 내용: 파일이 존재하지 않아서..."];

            if([logStr writeToFile:logPath atomically:false encoding:NSUTF8StringEncoding error:&err]){

                

                NSLog(@"Log Create!2");

            }

            else{

                NSLog(@"Log Create Err2 : %@",err);

            }

            


        

        }



예제2

 //- (BOOL) fileExistsAtPath : path isDirectory:(BOOL *)flag    파일이 디렉토리인지 구분한다.

  //  - (NSArray *) directoryContentsAtPath:path    디렉토리 내용을 가져온다.

    

    //- (BOOL) fileExistsAtPath:path    파일이 존재하는지를 확인한다.

    //- (NSData) contentsAtPath    파일에서 데이터를 읽는다.

    //- (BOOL) removeFileAtPath : path handler:handler    파일을 삭제한다.

    

    //현재경로

    NSFileManager *fm = [NSFileManager defaultManager];

    NSString *currentPath = [fm currentDirectoryPath];

    NSLog(@"viewdidload 현재경로 : %@" , currentPath);


    //다큐먼트 폴더가 존재하는지 확인

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

    NSLog(@"DocumentDrectory : %@" , DocumentDrectory[0]);

    

    //디렉토리 존재여부

    if ([fm isWritableFileAtPath:DocumentDrectory[0]]) {

        NSLog(@"Documents가 존재합니다.");

    }else{

        NSLog(@"Documents가 존재하지 않습니다.");

    }

    

    //파일이 존재하는지확인

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

    NSString *path2 = DocumentDrectory2[0];

    NSString *videoFilePath = [path2 stringByAppendingString:@"/output_2018-12-06_14-32-10.mov"];

    

    

    

    NSURL *fileURL = [NSURL fileURLWithPath:videoFilePath];

    NSData *data = [NSData dataWithContentsOfURL:fileURL];

    

    

    

    

    //파일이 존재하는 지 확인

    if ([fm fileExistsAtPath: videoFilePath]) {

        NSLog(@"파일이 존재합니다.");

    }else{

        NSLog(@"파일이 존재하지 않습니다.");

    }

    

    NSError *error3;

    [fm contentsOfDirectoryAtPath:@"/" error:&error3];

    NSLog(@"현재 경로 내용 : %@ ",   [fm contentsOfDirectoryAtPath:@"/" error:&error3]);

    

    

    NSError *error2;

    [fm contentsOfDirectoryAtPath:@"/" error:&error2];

    NSLog(@"현재 경로 내용 첫번째방: %@ ",   [[fm contentsOfDirectoryAtPath:@"/" error:&error2] objectAtIndex:0]);

    

    

    NSError *error;

    [fm contentsOfDirectoryAtPath:@"/" error:&error];

    NSLog(@"디렉토리 내용 : %@ ",   [fm contentsOfDirectoryAtPath: DocumentDrectory[0] error:&error]);

    

    NSLog(@"************************************************************************************************************");

    


    // create the route of localDocumentsFolder

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

    NSLog(@"filePaths array : %@" , filePaths);

    //("/var/mobile/Containers/Data/Application/F35B4D54-C559-4236-9AE2-C3E986708687/Documents")

    

    

    //first use the local documents folder

    NSString *docsPath = [NSString stringWithFormat:@"%@/Documents", NSHomeDirectory()];

    NSLog(@"docsPath  : %@" , docsPath);

    // /var/mobile/Containers/Data/Application/F35B4D54-C559-4236-9AE2-C3E986708687/Documents

    

    

    //then use its bundle, indicating its path

    NSString *bundleRoot = [[NSBundle bundleWithPath:docsPath] bundlePath];

    NSLog(@"bundleRoot  : %@" , bundleRoot);

    ///var/mobile/Containers/Data/Application/F35B4D54-C559-4236-9AE2-C3E986708687/Documents

    

    //then get its content

    NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:bundleRoot error:nil];

     NSLog(@"dirContents  : %@" , dirContents);

    //("output_2018-12-06_14-32-10.mov", "output_2018-12-06_14-38-05.mov")

    

    

    // this counts the total of jpg images contained in the local document folder of the app

    NSArray *onlyJPGs = [dirContents filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"self ENDSWITH '.mov'"]];

    

    // in console tell me how many jpg do I have

    NSLog(@"numero de fotos en total: %i", [onlyJPGs count]); //2

    // ---------------


    //*****************************************************************************

    

    

    


    

    

    

    //참고:

    //https://stackoverflow.com/questions/499673/getting-a-list-of-files-in-a-directory-with-a-glob




반응형

'ios 뽀개기 > objective-c' 카테고리의 다른 글

ios 루팅방지 체크 소스  (0) 2018.10.24
UIViewContorller의 수명주기 관리 메서드  (0) 2018.10.23
objective c 의 모든것  (5) 2018.07.28
objective c alert 구현  (0) 2018.07.28
객체지향 예제  (0) 2018.07.10

댓글