2013-01-25 155 views
1

我正試圖讀取放置在資源文件夾內的目錄Object Bank中的文件。無法讀取資源文件夾中的文件 - iOS

//Get path for file in object bank 
NSString* path = [[NSBundle mainBundle] pathForResource:fileId ofType:@"eam" inDirectory:@"Object Bank"]; 
NSError *error=nil; 

//Check if it is present at the location 
Boolean prepositioned=[[NSFileManager defaultManager] fileExistsAtPath:path]; 
NSLog(@"File Found : %@",[email protected]"Yes":@"No"); 

//This outputs "File Found : Yes" 

//Read file 
NSString *fileContents=[NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error]; 
NSLog(@"Prepostioned content length: %d",fileContents.length); 
//This outputs "Prepostioned content length: 0" 

//if file is present: 
if (!error) { 
    //Do something 

} 
else 
{ 
    //Print the error 
    NSLog(@"Error : %@",error.description); 
} 

,我發現了以下錯誤:

Error Domain=NSCocoaErrorDomain Code=261 "The operation couldn’t be completed. (Cocoa error 261.)" UserInfo=0x8c410d0 {NSFilePath=/Users/ctb/Library/Application Support/iPhone Simulator/6.0/Applications/16881651-3790-4C87-A3A0-1E1D60563684/OAS IPAD.app/Object Bank/70118600.eam, NSStringEncoding=4} 

的路徑不返回nil,即使該文件不存在,並且fileExistsAtPath:path總是返回是不管該文件是否存在或不存在。

我已經試過這還有:

NSArray *paths =[[NSBundle mainBundle] pathsForResourcesOfType:@"eam" inDirectory:@"Object Bank"]; 
for (NSString *path in paths) { 
    NSString *fileString=[NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil]; 
    NSLog(@"Resource : %u ",fileString.length); 
} 

但它也有同樣的問題。

+0

你想從ducument的目錄中讀取它嗎? –

回答

0

您未從Resources文件夾讀取。您正試圖從Object Bank目錄中讀取。返回nil是有道理的,因爲該文件不存在。

NSString *filePath = [[NSBundle mainBundle] pathForResource:fileId ofType:@"eam" inDirectory:@"Object Bank"]; 

NSFileManager *fileManager = [NSFileManager defaultManager]; 
    if ([fileManager fileExistsAtPath:filePath]) { 
     NSLog(@"file exist"); 
    } 

下面是我試圖讀取從資源目錄中名爲pk文本文件的截圖。希望能幫助到你。快樂編碼:-)

screenshot

+0

我想你誤會了我的問題... 我有一個名爲「對象銀行」資源文件夾內的文件夾。所需的文件可能存在也可能不存在。 但是即使它存在,我仍然無法讀取文件。 即使文件不存在,'fileExistsAtPath'也會返回yes。 –

0

要絕對,積極確保您的文件中讀取是NSUTF8StringEncoding,否則你就會有這種類型的錯誤,這是在沒有告訴你,這不是誤導由於不匹配編碼而被讀取。

用說TextWrangler打開你的文件(fileId類型爲eam)並檢查它有什麼編碼,然後在編碼參數中使用那個。

相關問題