我可以在路徑寫入文件:如何在iPhone設備上讀取文件?
NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docPath = [dirPaths objectAtIndex:0];
,但我無法讀取該文件。 我必須做什麼?
Regards
我可以在路徑寫入文件:如何在iPhone設備上讀取文件?
NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docPath = [dirPaths objectAtIndex:0];
,但我無法讀取該文件。 我必須做什麼?
Regards
上面列出的代碼只是爲您提供了文檔目錄的路徑。
您需要提供特定的文件...如:
if([dirPaths count] > 0)
{
NSString * documentsDirectory = [dirPaths objectAtIndex: 0];
if(documentsDirectory)
{
NSString * docPath = [NSString stringWithFormat: @"%@/TheFileIAmLookingFor.txt",
[dirPaths objectAtIndex:0]];
}
}
,然後嘗試類似:
NSString * contentsOfDocPath = [[NSString alloc] initWithContentsOfFile: docPath]
獲得文件的實際內容。
您正在編寫一個名稱爲某個目錄的文件。
當您想要讀取該文件時,必須告訴操作系統您要讀取哪個文件。
下面是枚舉目錄中文件的代碼,在本例中爲「Documents」目錄。
在某些時候,代碼必須做出關於哪些文件需要讀取的決定。
NSString *docsDir = [NSHomeDirectory() stringByAppendingPathComponent: @"Documents"];
NSFileManager *localFileManager = [NSFileManager defaultManager];
NSDirectoryEnumerator *dirEnum =
[localFileManager enumeratorAtPath:docsDir];
NSString *file;
while (file = [dirEnum nextObject]) {
if ([file isEqualToString: _The_NAME_YOU_ARE_LOOKING_FOR_]) {
NSString *fullPath = [NSString stringWithFormat:@"%@/%@", docsDir,file];
// READ YOUR FILE FROM HERE
NSDictionary *attrs = [localFileManager
attributesOfItemAtPath:fullPath error:&error];
if (error) {
NSLog(@" error - %@", error);
} else {
NSLog(@" file : %@", file);
NSInteger fsiz = [attrs fileSize];
NSString *ftyp = [attrs fileType];
NSDate *fmod = [attrs fileModificationDate];
NSInteger fperm= [attrs filePosixPermissions];
NSLog(@" %9d : %@ : %@ : %@ : %d", fsiz, file, ftyp, fmod, fperm);
}
}
}
我可以在完整路徑「.../Documents/sdtest.txt」上編寫文件。這個文件存在,我在Organizer「Sanbox中的數據文件」中看到它。但是當我讀取它時,使用相同的文件名「.../Documents/sdtest.txt」 - 在rcv緩衝區中沒有返回數據。在iPhone模擬器中,這是沒有問題的,我可以將文件夾權限更改爲「讀寫」。但我不知道,我必須在設備上做什麼。 – theWalker 2012-01-18 19:41:08
我在上面的答案中添加了一些代碼,用於轉儲目錄中所有文件的屬性,包括大小和權限。確保您的文件實際上具有非零大小。 – Rayfleck 2012-01-18 20:32:55
您是否驚訝不能打開目錄? – v1Axvw 2012-01-18 19:11:39
我可以打開目錄,我可以寫入文件,但讀取失敗 - 在rcv緩衝區中沒有數據。 – theWalker 2012-01-18 19:12:53