我正在尝试读取放在资源文件夹内目录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);
}
但是它有同样的问题。
绝对肯定地确保您要读取的文件是NSUTF8StringEncoding,否则您将遇到此类型的错误,这会误导您没有告诉您由于编码不匹配而导致无法读取该文件。
使用“ TextWrangler”打开您的文件(eam类型的fileId),并检查其编码,然后在encoding参数中使用该编码。
您不是从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
的文本文件的屏幕截图。希望能帮助到你。快乐的编码:-)
我必须在网址中添加file://
前缀
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
}