2

我正在尝试读取位于Object Bank资源文件夹内的目录中的文件。

//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 : %@",prepositioned?@"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无论文件是否存在,总是返回 yes。

我也试过这个:

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);
}

但它有同样的问题。

4

3 回答 3

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从资源目录命名的文本文件的屏幕截图。希望能帮助到你。快乐编码:-)

截屏

于 2013-01-25T06:35:29.237 回答
0

绝对肯定地确保您要读取的文件是 NSUTF8StringEncoding,否则您将遇到此类错误,这会误导您不告诉您由于编码不匹配而未读取它。

使用 TextWrangler 打开您的文件(eam 类型的文件 ID)并检查它的编码,然后在编码参数中使用该编码。

于 2015-06-06T00:08:34.190 回答
0

我必须将file://前缀添加到 url

guard let resourceString = Bundle.main.resourcePath,
    let fileURL = URL(string: "file://\(resourceString)/mock.txt") else {

    print(">>> url fail")
    return
}

do {

    let data = try Data(contentsOf: fileURL)
    let string = String(data: data, encoding: .utf8)

    print(">>> \(string)")

} catch let error {

    print(">>> failed: \(error)")
    return
}
于 2019-11-03T09:51:11.680 回答