2011年12月14日 星期三

simple file management under bundle document directory 簡單的檔案管理

簡單的檔案管理

To manage the files under application's bundle document directory:


NSString *docRoot ;

// 獲取 app文件夾的位置

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

docRoot = [paths objectAtIndex:0];


// 檢查app文件夾下 myfile.png 這個檔案是否存在

// to test existence of a file "myfile.png"

NSString *myFilePath = [[docRoot stringByAppendingPathComponent:@"myfile.png"]];

if ([[NSFileManager defaultManager] fileExistsAtPath: myFilePath]) {

NSLog(@"myfile.png is here!!");

}

else NSLog(@"myfile.png is not in document folder.");


// 刪除app文件夾下 myfile.png 這個檔案

// to delete the file "myfile.png"

if ([[NSFileManager defaultManager] removeItemAtPath:myFilePath error:&error]) {

NSLog(@"file deleted");

}

else NSLog(@"Delete file error: %@", error);


// 建立子資料夾

// to create sub-directory

NSString * subDirectory = [[docRoot stringByAppendingPathComponent:@"mySubDir"]];

if (![[NSFileManager defaultManager] fileExistsAtPath: subDirectory]) {

/* directory doesn't exist, create it. */

if ([[NSFileManager defaultManager] createDirectoryAtPath:subDirectory

withIntermediateDirectories:NO

attributes:nil

error:&error]) {

NSLog(@"directory %@ created.", subDirectory);

}

else {

NSLog(@"Create directory error: %@", error);

}

}


// 刪除子資料夾

// to delete sub-directory

if ([[NSFileManager defaultManager] fileExistsAtPath:subDirectory]) {

// subDirectory exist, delete it.

if ([[NSFileManager defaultManager] removeItemAtPath:subDirectory error:&error]) {

NSLog(@"subDirectory %@ deleted.",subDirectory) ;

}

else {

NSLog(@"Delete directory error: %@", error);

}

}


// 列出app文件夾下的檔案
// list out all files under apple document directory

NSArray *directoryContent = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:subDirectory error:NULL];

for (int count = 0; count < (int)[directoryContent count]; count++) {

NSLog(@"#%d: %@", (count + 1), [directoryContent objectAtIndex:Count]);

}





沒有留言:

張貼留言