2009-09-30 207 views
9

我是iPhone編程的新手。我想讀取位於資源文件夾子文件夾中的文本文件的內容。iPhone:獲取資源文件夾子文件夾內的文件路徑

資源文件夾結構如下:

資源

  1. Folder1中----> DATA.TXT
  2. FOLDER2 ----> DATA.TXT
  3. Folder3-- - > Folder1 ----> Data.txt

有多個名爲「Data.txt」的文件,所以如何訪問每個文件夾中的文件?我知道如何閱讀文本文件,但是如果資源結構與上述結構類似,那我該如何獲得路徑?

例如,如果我想從Folder3訪問「Data.txt」文件,如何獲取文件路徑?

請建議。

回答

12

要繼續psychotiks回答一個完整的例子是這樣的:

NSBundle *thisBundle = [NSBundle bundleForClass:[self class]]; 
NSString *filePath = nil; 

if (filePath = [thisBundle pathForResource:@"Data" ofType:@"txt" inDirectory:@"Folder1"]) { 

    theContents = [[NSString alloc] initWithContentsOfFile:filePath]; 

    // when completed, it is the developer's responsibility to release theContents 

} 

注意,您可以使用-pathForResource:ofType:inDirectory訪問子目錄ressources。

+0

但在不同的文件夾中有多個具有相同名稱的文件夾。所以在這種情況下,如何實現路徑 – Rupesh 2009-09-30 08:32:06

+4

@Rupesh:對於您需要使用的第二個文件夾:'[thisBundle pathForResource:@「Data」ofType:@「txt」inDirectory:@「Folder3/Folder1」]'。注意'inDirectory:'參數是相對於捆綁根目錄的。 – PeyloW 2009-09-30 08:53:12

+1

你應該真的使用'[NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL]',這樣內存就是_「managed」_,更重要的是''initWithContentsOfFile:'從Mac OS X 10.4開始已經被棄用了,**可在iPhone OS **上使用。所以代碼只能在模擬器中工作。 – PeyloW 2009-09-30 08:58:16

4
NSBundle* bundle = [NSBundle mainBundle]; 
    NSString* path = [bundle bundlePath]; 

這可以爲您提供捆綁的路徑。從那裏開始,你可以導航你的文件夾結構。

16

您的「資源文件夾」實際上是您的主包的內容,也稱爲應用程序包。您使用pathForResource:ofType:pathForResource:ofType:inDirectory:來獲取資源的完整路徑。

如果您想保留一個字符串,則以stringWithContentsOfFile:encoding:error:方法將一個文件的內容作爲字符串加載,該方法對於自動釋放的字符串爲initWithContentsOfFile:encoding:error:

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Data" 
                ofType:@"txt" 
               inDirectory:@"Folder1"]; 
if (filePath != nil) { 
    theContents = [NSString stringWithContentsOfFile:filePath 
              encoding:NSUTF8StringEncoding 
              error:NULL]; 
    // Do stuff to theContents 
} 

這與Shirkrin之前給出的答案几乎相同,但是它與目標方法略有不同。這是因爲initWithContentsOfFile:在Mac OS X上已棄用,並且在所有iPhone OS上都不可用。

7

Shirkrin's answerPeyloW's answer上面都是有用的,我設法使用pathForResource:ofType:inDirectory:訪問我的應用程序包中不同文件夾中具有相同名稱的文件。

我還發現了一個替代解決方案here,它適合我的要求略好,所以我想我會分享它。具體見this link

例如,假設我有以下文件夾引用(藍色圖標,組是黃色):

enter image description here

然後我就可以訪問該圖像文件是這樣的:

NSString * filePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"pin_images/1/2.jpg"]; 
UIImage * image = [UIImage imageWithContentsOfFile:filePath]; 

由於一個側面說明,pathForResource:ofType:inDirectory:等效看起來像這樣:

NSString * filePath = [[NSBundle mainBundle] pathForResource:@"2" ofType:@"jpg" inDirectory:@"pin_images/1/"]; 
+0

謝謝。工作正常 – 2016-03-15 12:28:45

相關問題