2012-01-18 88 views
-3

我可以在路徑寫入文件:如何在iPhone設備上讀取文件?

NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *docPath = [dirPaths objectAtIndex:0]; 

,但我無法讀取該文件。 我必須做什麼?

Regards

+2

您是否驚訝不能打開目錄? – v1Axvw 2012-01-18 19:11:39

+0

我可以打開目錄,我可以寫入文件,但讀取失敗 - 在rcv緩衝區中沒有數據。 – theWalker 2012-01-18 19:12:53

回答

1

上面列出的代碼只是爲您提供了文檔目錄的路徑。

您需要提供特定的文件...如:

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] 

獲得文件的實際內容。

+0

我可以在此路徑(docPath)上編寫具有自己名稱的任何文件,但我無法讀取它。在模擬器上,我可以更改Mac文件夾權限,並且讀取操作都可以。但是我必須在物理設備上做什麼? – theWalker 2012-01-18 19:18:51

+1

我的回答很有希望給你一些好的線索。您正試圖讀取目錄,而不是特定的文件。學習如何從iPhone上的文件中讀取,你會有一個更快樂的時間。 – 2012-01-18 19:26:28

+0

如果我寫文件(這是我的問題) - 路徑和文件名都可以。我的問題是關於不同的問題。 – theWalker 2012-01-18 19:36:17

1

您正在編寫一個名稱爲某個目錄的文件。
當您想要讀取該文件時,必須告訴操作系統您要讀取哪個文件。

下面是枚舉目錄中文件的代碼,在本例中爲「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); 
      } 
     } 
    } 
+0

我可以在完整路徑「.../Documents/sdtest.txt」上編寫文件。這個文件存在,我在Organizer「Sanbox中的數據文件」中看到它。但是當我讀取它時,使用相同的文件名「.../Documents/sdtest.txt」 - 在rcv緩衝區中沒有返回數據。在iPhone模擬器中,這是沒有問題的,我可以將文件夾權限更改爲「讀寫」。但我不知道,我必須在設備上做什麼。 – theWalker 2012-01-18 19:41:08

+0

我在上面的答案中添加了一些代碼,用於轉儲目錄中所有文件的屬性,包括大小和權限。確保您的文件實際上具有非零大小。 – Rayfleck 2012-01-18 20:32:55

相關問題